Array sum not printing in recursive function - c++

I wrote a recursive function that returns the sum of the array when called. This is my code:
#include <iostream>
struct array {
int A[10];
int size;
int length;
};
void displayArray(struct array arr) {
std::cout << "the elements are :-" << std:: endl << '\t';
for (int i = 0; i < arr.length; i++) {
std::cout << arr.A[i] << ',';
}
std::cout << std::endl;
}
int i = 0;
int sum(int* a, int length) {
// Size of an int element.
int j = 4;
if (i < length) {
return a[i+1] + sum((a + j), length);
}
else {
return 0;
}
}
int main()
{
struct array arr = {{1,2,3,4,5,6,7}, 10, 7};
int* p;
std::cout<< sum(&arr.A[0],arr.length );
}
However, it is not returning anything and also, I ran it on an online compiler. It is not showing any error or warning, but it's not showing any output either.

well in this
int i = 0;
int sum(int* a, int length) {
int j = 4;
if (i < length) {
//std::cout << a[i];
return a[i] + sum((a + j), length);
}
}
your exit condition is i >= length, but you never change i so this will keep recursing till you run out of stack space. Since this is a very strange function (I mean why is j = 4) I cant suggest a solution, only why it doesnt work at present
here is the error on my dev box
Unhandled exception at 0x00007FF711A9297E in ConsoleApplication2.exe: 0xC00000FD: Stack overflow (parameters: 0x0000000000000001, 0x0000003E526B3FA8).

You are running in an endless loop because of your if condition never reaching an end.
Besides this, the global i and the local j are both superflous.
Maybe it would be easier to use your length to access the array and as an end marker and decrease it with each call of sum
int sum(int* a, int length){
if (--length >= 0)
return a[length] + sum(a, length);
else
return 0;
}
by the way, I would recommend using
`std::array <int, 10> a= {1,2,3,4,5,6,7};'
instead of your struct including int A[10];
this gives you out of bounds checking, iterators for your collection, no need for C pointer algorithmics, ...

Related

Getting sigabrt error in heapsort program

I am getting sigabrt error as given below for the given heapsort program. I am new to programming so I apologize for silly mistakes.
error : Abort signal from abort(3) (SIGABRT)
The major parts of the code are as follows
heapify - a program to make a heap out of the given array
heapsort - a function which sorts the array according to a heap and saves the result in the array
main - the driver function
#include <iostream>
#include <math.h>
using namespace std;
void swapper (int first, int second) {
int temp;
temp = second;
second = first;
first = temp;
}
void heapify (int a[], int size) {
for(int i = 0; i < (size/2) ; i++) {
int left = 2*i;
int right = 2*i + 1;
if (a[i] < a[left]) {
swap(a[i], a[left]);
}
else if (a[i] < a[right]) {
swap(a[i],a[right]);
}
}
}
void heapsort(int a[], int size){
int treesize = size;
int i = size;
heapify(a,size);
while (treesize > 0) {
cout << " \t " << a[i];
swap(a[i],a[0]);
i --;
treesize--;
heapify(a, treesize);
}
cout <<"\n";
for(int i = 0; i < size; i++) {
cout <<"\t"<<a[i];
}
}
int main() {
// your code goes here
int a[] = {10,1,2,11,4,57,12,13,44,14,6,7,9,8,15,16,17,98};
int arrsize= sizeof(a)/(sizeof(a[0]));
int pos;
int ele = 7;
heapsort(a,arrsize);
for (int i = 0; i < arrsize; i++){
cout <<"\n "<<a[i];
cout<<"\n"<<arrsize;
}
return 0;
}
I'm not sure about the correctness of the rest of the program, but the reason why you're getting the exception is because you're accessing memory out of bounds. You call heapsort with the array size like this:
heapsort(a, arrsize);
And then you set treesize and i to that size:
int treesize = size;
int i = size;
And then in those lines:
cout << " \t " << a[i];
swap(a[i], a[0]);
i is still equal to arraysize. But it can at most be arraysize-1. This causes undefined behavior when you print a[i], and even worse, undefined behavior in the following line that modifies values outside of the array. On my machine, the former prints rubbish values and the latter causes stack corruption. Instead, you should set those values like this:
int treesize = size-1;
int i = size-1;
This fixes the print and the exception.

C++ Program To Find Smallest and Largest Number In Array

Beginner in C++ here and learning arrays. The program below is supposed to return the smallest and largest number in an array using two separate functions. One for the largest and one for the smallest number. However, it is returning 0 all the time for function lastLowestIndex and I am unsure what I may be doing wrong.
Could someone ever so kindly advice and show me what is incorrect in that function and what can be done to correct it so that it returns the correct value? I am obviously not seeing and/or understanding what is incorrect.
Thank you so very much for your help and time in advance!!!
#include <iostream>
#include <cstdlib>
int lastLargestIndex(int [], int);
int lastLowestIndex(int [], int );
using namespace std;
int main()
{
const int N = 15;
int arr[N] = {5,198,76,9,4,2,15,8,21,34,99,3,6,13,61};
int location;
//int location2;
location = lastLargestIndex( arr, N );
cout << "The last largest number is:" << location << endl;
location = lastLowestIndex(arr, N);
cout << "The last smallest number is:" << location << endl;
// std::system ("pause");
return 0;
}
int lastLargestIndex( int arr[], int size )
{
int highNum = 0;
for( int i = 0; i < size; i++ )
{
if ( arr[i] > highNum )
{
highNum = arr[i];
}
}
return highNum;
}
int lastLowestIndex(int arr[], int size)
{
int smallest = 0;
for (int i = 0; i < size; i++)
{
if (arr[i] < smallest)
{
smallest = arr[i];
}
}
//cout << smallest << '\n';
return smallest;
}
However, it is returning 0 all the time for function lastLowestIndex and I am unsure what I may be doing wrong.
You got a logic error when you initialised smallest to 0 in function lastLowestIndex() - that way if (arr[i] < smallest) condition is not evaluated to true if all input is positive. Instead, you should initialise it to the first member of array arr. The function should look like this:
int lastLowestIndex(int arr[], int size)
{
int smallest = arr[0];
for (int i = 0; i < size; i++)
{
if (arr[i] < smallest)
{
smallest = arr[i];
}
}
return smallest;
}
lastLowestIndex() initialises smallest to be 0, and then compares all elements of the array (which are positive, in your example) with it. All positive values are greater than zero, so smallest will remain zero.
Note that your logic is also not general for finding the maximum. Consider what the code will do if all elements of the array are negative.
You would be better off adopting a logic that does not make any assumptions about the array, other than its size and that it contains integral values. For example;
int lastLargestIndex( int arr[], int size )
{
int highNum = arr[0];
for( int i = 1; i < size; i++ )
{
if ( arr[i] > highNum )
{
highNum = arr[i];
}
}
return highNum;
}
This doesn't exhibit the problems yours does, since it initialises highNum with the first element of the array, and iterates over the rest (if any). This does assume size is positive.
Your functions are also named in a misleading manner, since they (attempt to) return the maximum (or minimum) value in the array, but their name suggests they will return the index of that value. I'll leave resolving that little issue as an exercise.
This is the correct working code!
#include <iostream>
#include <cstdlib>
int lastLargestIndex(int [], int);
int lastLowestIndex(int [], int );
using namespace std;
int main()
{
const int N = 15;
int arr[N] = {5,198,76,9,4,2,15,8,21,34,99,3,6,13,61};
int location;
location = lastLargestIndex( arr, N );
cout << "The last largest number is:" << location << endl;
location = lastLowestIndex(arr, N);
cout << "The last smallest number is:" << location << endl;
// std::system ("pause");
return 0;
}
int lastLargestIndex( int arr[], const int size )
{
int highNum = -100001;
for( int i = 0; i < size; i++ )
{
if ( arr[i] > highNum )
{
highNum = arr[i];
}
}
return highNum;
}
int lastLowestIndex(int arr[], const int size)
{
int smallest = 100001;
for (int i = 0; i < size; i++)
{
if (arr[i] < smallest)
{
smallest = arr[i];
}
}
//cout << smallest << '\n';
return smallest;
}
Modifications done:
Replaced argument in function from int size to const int size, since N is declared as const int in main function
Replaced highNum with -100001
Replaced smallest with 100001

Swapping Pointers of Array

#include <iostream>
#include <cstdlib>
using namespace std;
void swapNum(int *q, int *p)
{
int temp;
temp = *q;
*q = *p;
*p = temp;
}
void reverse(int *ip, int const size)
{
for (int k = 0; k < size; k++)
{
if (k == (size/2))
{
int *q = &ip[k];
int *p = &ip[k+1];
swapNum(q,p);
break;
}
else
swap(ip[k], ip[size-k]);
}
}
int main()
{
const int size = 20;
int arr[size];
int *ip;
ip = arr;
cout << "Please enter 20 different numbers." << endl;
for (int i = 0; i < size; i++)
{
cout << "\nNumber " << i+1 << " = ";
cin >> ip[i];
}
reverse(ip, size);
cout << "I will now print out the numbers in reverse order." << endl;
for (int j = 0; j < size; j++)
{
cout << ip[j] << " ";
}
return 0;
}
When I try to run this program it crashes. I don't know what's wrong and the purpose of my program is to swap number of the array using pointers. I am recently introduced to this so I am not that familiar with it. But I think that I am swapping the address of the numbers instead of swapping the numbers in the address. Correct me if I am wrong.
You're accessing outside the array bounds in reverse() when you do:
swap(ip[k], ip[size-k]);
On the first iteration of the for loop, k is 0 and size-k is size. But array indexes run from 0 to size-1. So it should be:
swap(ip[k], ip[size-k-1]);
But I don't see a definition of swap in your program. I think it should actually be:
swapNum(&ip[k], &ip[size-k-1]);
Another improvement: Instead of handling size == k/2 specially and using break, just use size < k/2 as the bound test in the for loop.
swap(ip[k], ip[size-k]);
Your problem is there. size - k when k is 0 will lead to undefined behavior (accessing an array out of bounds). Your loop structure in reverse can be simplified:
for (int k = 0; k < size / 2; k++)
swapNum(&ip[k], &ip[size - k - 1]); // updated to use the address since your swap function takes pointers.
Function reverse is invalid
void reverse(int *ip, int const size)
{
for (int k = 0; k < size; k++)
{
if (k == (size/2))
{
int *q = &ip[k];
int *p = &ip[k+1];
swapNum(q,p);
break;
}
else
swap(ip[k], ip[size-k]);
}
}
For example when k is equal to 0 then you call
swap(ip[0], ip[size]);
However the array has no element with index size.
ALso you mess two functions std::swap and swapNum
This code snippet also is invalid
if (k == (size/2))
{
int *q = &ip[k];
int *p = &ip[k+1];
swapNum(q,p);
break;
}
When size is an even number (or an odd number) as in your code then you make incorrect swap. For example if size is equal to 20 then you should swap ip[9[ with ip[10]. However according to the code snippet above you swap ip[10] with ip[11].
You could use standard algorithm std::reverse
for example
#include <algorithm>
#include <iterator>
//...
std::reverse( std::begin( arr ), std::end( arr ) );
or
#include <algorithm>
//...
std::reverse( arr, arr + size );
If you want to write the function yourself then it could look as
void reverse( int a[], int size )
{
for (int k = 0; k < size / 2; k++)
{
int tmp = a[k];
a[k] = a[size-k-1];
a[size-k-1] = tmp;
}
}
Or if you want to use your function swapNum then
void reverse( int a[], int size )
{
for (int k = 0; k < size / 2; k++)
{
swapNum( &a[k], &a[size-k-1] );
}
}
EDIT: I removed qualifier const from the first parameter that was a typo.

FirstChance Exception StackOverFlow Merge Sort Shell Sort Bubble Sort

Hey guys I'm working on some sorts and am trying to implement a bubble sort, a merge sort, and a shell sort. I use an outdated technique but I was wondering if you guys could let me know why I keep getting the following error:
First-chance exception at 0x01135EF7 in sortApplication2.exe: 0xC00000FD: Stack overflow (parameters: 0x00000000, 0x00542000).
Unhandled exception at 0x01135EF7 in sortApplication2.exe: 0xC00000FD: Stack overflow (parameters: 0x00000000, 0x00542000).
I am using Visual Studio 2012 if that plays any part. My code is in three different files so I'll post each separately.
My header file:
#pragma once
class sort
{
public:
sort();
void random1(int array[]);
void random2(int array[]);
void random3(int array[]);
void bubbleSort(int array[], int length);
/*void merge(int *input, int p, int r);
void merge_sort(int *input, int p, int r);*/
void shellSort(int array[], int length);
};
My class implementation file:
#include "sort.h"
#include <time.h>
#include <iostream>
using namespace std;
sort::sort()
{}
void sort::random1(int array[])
{
// Seed the random-number generator with current time so that
// the numbers will be different every time the program runs.
for(int i = 0; i < 25; i++)
{
srand ((unsigned) time(NULL));
int n = rand(); //generates a random number
array[i] = n; //places it into the array
}
}
void sort::random2(int array[])
{
// Seed the random-number generator with current time so that
// the numbers will be different every time the program runs.
for(int i = 0; i < 10000; i++)
{
srand ((unsigned) time(NULL));
int n = rand(); //generates a random number
array[i] = n; //places it into the array
}
}
void sort::random3(int array[])
{
// Seed the random-number generator with current time so that
// the numbers will be different every time the program runs.
for(int i = 0; i < 100000; i++)
{
srand ((unsigned) time(NULL));
int n = rand(); //generates a random number
array[i] = n; //places it into the array
}
}
void sort::bubbleSort(int array[], int length)
{
//Bubble sort function
int i,j;
for(i = 0; i < 10; i++)
{
for(j = 0; j < i; j++)
{
if(array[i] > array[j])
{
int temp = array[i]; //swap
array[i] = array[j];
array[j] = temp;
}
}
}
}
/*void sort::merge(int* input, int p, int r) //the merge algorithm of the merge sort
{
int mid = (p + r) / 2;
int i1 = 0;
int i2 = p;
int i3 = mid + 1;
// Temp array
int x = r -p + 1;
int *temp;
temp = new int [x];
// Merge in sorted form the 2 arrays
while ( i2 <= mid && i3 <= r )
if ( input[i2] < input[i3] )
temp[i1++] = input[i2++];
else
temp[i1++] = input[i3++];
// Merge the remaining elements in left array
while ( i2 <= mid )
temp[i1++] = input[i2++];
// Merge the remaining elements in right array
while ( i3 <= r )
temp[i1++] = input[i3++];
// Move from temp array to master array
for ( int i = p; i <= r; i++ )
input[i] = temp[i-p];
}
void sort::merge_sort(int *input, int p, int r) //the merge sort algorithm
{
if ( p < r ) //When p and r are equal the recursion stops and the arrays are then passed to the merge function.
{
int mid = (p + r) / 2;
merge_sort(input, p, mid); //recursively calling the sort function in order to break the arrays down as far as possible
merge_sort(input, mid + 1, r);//recursively calling the sort function in order to break the arrays down as far as possible
merge(input, p, r); //merge function realigns the smaller arrays into bigger arrays until they are all one array again
}
}*/
void sort::shellSort(int array[], int length) //Shell sort algorithm
{
int gap, i, j, temp;
for( gap = length / 2; gap > 0; gap /= 2) //gap is the number of variables to skip when doing the comparisons
{
for( i = gap; i < length; i++) //This for loop sets the variable to use as the gap for the comparisons
{
for (j = i - gap; j >= 0 && array[j] > array[j + gap]; j -= gap)
{
temp = array[j]; //the array variables are swapped
array[j] = array[j + gap];
array[j + gap] = temp;
}
}
}
}
And my driver file:
#include "sort.h"
#include <iostream>
using namespace std;
int main()
{
int bubbleArray1[25]; //these are the arrays to be sorted. three for each sort. each has a length of 25, 10000, or 100000.
int bubbleArray2[10000];
int bubbleArray3[100000];
int mergeArray1[25];
int mergeArray2[10000];
int mergeArray3[100000];
int shellArray1[25];
int shellArray2[10000];
int shellArray3[100000];
sort Sorts;
Sorts.random1(bubbleArray1);
Sorts.random1(mergeArray1);
Sorts.random1(shellArray1);
Sorts.random2(bubbleArray2);
Sorts.random2(mergeArray2);
Sorts.random2(shellArray2);
Sorts.random3(bubbleArray3);
Sorts.random3(mergeArray3);
Sorts.random3(shellArray3);
cout << "BubbleSort1 is now being sorted.\n";
Sorts.bubbleSort(bubbleArray1, 25);
cout << "BubbleSort2 is now being sorted.\n";
Sorts.bubbleSort(bubbleArray2, 10000);
cout << "BubbleSort3 is now being sorted.\n";
Sorts.bubbleSort(bubbleArray3, 100000);
cout << "End bubble sorts.\n";
/*cout << "MergeSort1 is now being sorted.\n";
Sorts.merge_sort(mergeArray1, 0, 25);
cout << "MergeSort2 is now being sorted.\n";
Sorts.merge_sort(mergeArray2, 0, 10000);
cout << "MergeSort3 is now being sorted.\n";
Sorts.merge_sort(mergeArray3, 0, 100000);
cout << "End merge sorts.\n";*/
cout << "ShellSort1 is now being sorted.\n";
Sorts.shellSort(shellArray1, 25);
cout << "ShellSort1 is now being sorted.\n";
Sorts.shellSort(shellArray2, 10000);
cout << "ShellSort1 is now being sorted.\n";
Sorts.shellSort(shellArray3, 100000);
cout << "End shell sorts.\n";
cout << "Array\tElements\n";
cout << "BubbleSort1\t";
for(int i = 0; i < 25; i++)
{
cout << bubbleArray1[i] << " ";
}
cout << "\nMergeArray1\t";
for(int i = 0; i < 25; i++)
{
cout << mergeArray1[i] << " ";
}
cout << "\nShellArray1\t";
for(int i = 0; i < 25; i++)
{
cout << shellArray1[i] << " ";
}
return 0;
}
I know it's a lot of code. And there are probably many ways I could make the code better.
I would just like to know what's causing the error up above since I can't find it using my compiler.
You are allocating too much memory on the stack. Variables with 'automatic' storage class go on the stack. Allocate heap instead.
So, instead of:
int shellArray3[100000];
Do:
int* shellArray3 = new int[100000];
Or better yet, use std::vector.
If you don't want to use heap memory, you could also use the static storage class for something like this. To do that:
static int shellArray3[100000];
That will allocate one instance of the variable for the whole program rather than allocating a copy for each function entry on the stack.

Superfluous characters printed by cout when using exception::what()

I'm sure this is pretty simple, but I couldn't really devise a search query which helped me resolve the issue.
I'd almost be inclined to think this was a bug in the Windows command prompt, except that I've never seen it before, until I started using exceptions, where it occurs if and only if I use exception::what().
This is for a homework assignment, and the program is supposed to compute a series of given problems and display the answers. All of the problems are in a similar vein (matrix/vector arithmetic), and the only ones which cause problems are the problems which are intentionally designed to generate errors, since that's the only time exception::what() is used.
Here's one of the offending problems:
(By the way, is it OK to arbitrarily place these
problems into blocks so that the objects go out of scope and the destructors are called before the next problem, as I've done?)
{ // Problem #9
Vector v1(5);
Matrix m1(3, 3, 1);
try {
v1.set(1, -2);
v1.set(2, -1);
v1.set(3, 4);
v1.set(4, 9);
v1.set(5, 3);
m1.set(1, 1, 12);
m1.set(1, 2, 36);
m1.set(1, 3, -7);
m1.set(2, 1, 4);
m1.set(2, 3, 11);
m1.set(3, 1, 7);
m1.set(3, 2, -5);
m1.set(3, 3, -2);
Vector * ans9 = product(m1, v1);
cout << "Answer to problem 9:" << endl;
ans9->print();
delete ans9;
}
catch(exception & ex) {
cout << "Exception in problem 9: " << ex.what() << endl;
}
} // End problem 9
cout << endl << endl;
The Matrix class and its constructor are nothing special, and the code doesn't throw any exceptions there, so I'll just share the offending product() function:
Vector * product(Matrix &m, Vector &v) {
unsigned int vLength = v.getLength(), mRows = m.getRows(), mCols = m.getCols();
if ( mCols != vLength ) {
throw std::logic_error("matrix/vector product impossible (size mismatch)!");
}
Vector * vprod = new Vector(mRows);
for (unsigned int i = 1; i <= mRows; ++i) {
double value = 0;
for (unsigned int j = 1; j <= vLength; ++j) {
value += (m.get(i, j)) * (v.get(j));
}
vprod->set(i, value);
}
return vprod;
}
And here's an example of the kind of output I get:
I left that ! in there so you can see that it is just printing whatever the last character was right on down that column, until some other character is explicitly printed there.
So, what exactly is going on here? I figure it's probably something to do with string termination, but maybe that's just because I've had too much fun with C in the past.
EDIT: Folks asked for a compilable code segment, and the best I could do was 228 lines. Here goes:
#include <iostream>
#include <iomanip>
#include <cstdlib>
using std::cout;
using std::endl;
using std::exception;
class Vector {
private:
unsigned int length;
double *elements;
public:
Vector(unsigned int desiredLength);
~Vector();
//void dDestroy(Vector &v);
unsigned int getLength();
void set(unsigned int position, double value);
double get(unsigned int position);
void print();
};
Vector::Vector(unsigned int desiredLength) {
length = desiredLength;
elements = new double[length];
for (unsigned int i = 0; i < length; ++i) {
elements[i] = 0;
}
}
Vector::~Vector() {
delete[] elements;
}
unsigned int Vector::getLength() {
return length;
}
void Vector::set(unsigned int position, double value) {
if (position > length || position <= 0) {
throw std::logic_error("vector set failed (out of range)");
}
--position;
elements[position] = value;
}
double Vector::get(unsigned int position) {
if (position > length || position <= 0) {
throw std::logic_error("vector get failed (out of range)");
}
--position;
return elements[position];
}
void Vector::print() {
std::cout << "[ ";
for (unsigned int i=0; i < length; ++i) {
std::cout << elements[i] << " " ;
}
std::cout << "]";
}
class Matrix {
private:
unsigned int rows, cols;
double **elements;
public:
Matrix(unsigned int desiredRows, unsigned int desiredCols, double defaultValue);
~Matrix();
unsigned int getRows();
unsigned int getCols();
void set(unsigned int i, unsigned int j, double value);
double get(unsigned int i, unsigned int j);
void print();
};
Matrix::Matrix(unsigned int desiredRows, unsigned int desiredCols, double defaultValue) {
rows = desiredRows, cols = desiredCols;
// Create
elements = new double*[rows];
for (unsigned int i = 0; i < rows; ++i) {
elements[i] = new double[cols];
}
// Initialize
for (unsigned int i = 0; i < rows; ++i) {
for (unsigned int j = 0; j < cols; ++j) {
elements[i][j] = defaultValue;
}
}
}
Matrix::~Matrix() {
for (unsigned int i = 0; i < rows; ++i) {
delete[] elements[i];
}
delete[] elements;
}
unsigned int Matrix::getRows() {
return rows;
}
unsigned int Matrix::getCols() {
return cols;
}
void Matrix::set(unsigned int i, unsigned int j, double value) {
if (i > rows || j > cols) {
throw std::logic_error("matrix set failed (out of range).");
}
--i, --j;
elements[i][j] = value;
}
double Matrix::get(unsigned int i, unsigned int j) {
if (i > rows || j > cols || i <= 0 || j <= 0) {
throw std::logic_error("matrix get failed (out of range).");
}
--i, --j;
return elements[i][j];
}
void Matrix::print() {
// TODO it would be nice to format based on maximum digits in any value
for (unsigned int i = 0; i < rows; ++i) {
std::cout << "[ ";
for (unsigned int j = 0; j < cols; ++j) {
std::cout << std::setprecision(2) << elements[i][j] << " ";
}
std::cout << "]\n";
}
}
Vector * dot(Vector &v1, Vector &v2) {
if (v1.getLength() != v2.getLength() ) {
throw std::logic_error("dot product impossible (length mismatch)");
}
double result = 0;
for (unsigned int i = 1; i <= v1.getLength(); ++i) {
result += (v1.get(i) * v2.get(i));
}
Vector * vdot = new Vector(1);
vdot->set(1, result);
return vdot;
}
Vector * product(Matrix &m, Vector &v) {
unsigned int vLength = v.getLength(), mRows = m.getRows(), mCols = m.getCols();
if ( mCols != vLength ) {
throw std::logic_error("matrix/vector product impossible (size mismatch)");
}
Vector * vprod = new Vector(mRows);
for (unsigned int i = 1; i <= mRows; ++i) {
double value = 0;
for (unsigned int j = 1; j <= vLength; ++j) {
value += (m.get(i, j)) * (v.get(j));
}
vprod->set(i, value);
}
return vprod;
}
Vector * dot(Vector &v1, Vector &v2);
Vector * product(Matrix &m, Vector &v);
int main() {
cout << endl;
{ // Problem #1
Vector v1(3), v2(3);
try {
v1.set(1, 2);
v1.set(2, 1);
v1.set(3, 3);
v2.set(1, 0);
v2.set(2, 4);
v2.set(3, -9);
Vector * ans1 = dot(v1, v2);
cout << "Answer to problem 1:" << endl;
ans1->print();
delete ans1;
}
catch(const exception & ex) {
cout << "Exception in problem 1: " << ex.what() << endl;
}
} // End problem 1
cout << endl << endl;
{ // Problem #2
Vector v1(2), v2(3);
try {
v1.set(1, 12);
v1.set(2, 1);
v2.set(1, 3);
v2.set(2, -1);
v2.set(3, 5);
Vector * ans2 = dot(v1, v2);
cout << "Answer to problem 2:" << endl;
ans2->print();
delete ans2;
}
catch(const exception & ex) {
cout << "Exception in problem 2: " << ex.what() << endl;
}
} // End problem 2
cout << endl << endl;
}
OK, the comments get a bit crowed and the following is a little to explicit for a comment anyway, so please forgive the not-exactly-an-answer-style of the following.
Since the extra "!" also apears in the line with the prompt, after the program has already exited, it is rather unlikely, that it has something to do with your application. It could be a faulty display driver, or some issue with the Client Server Runtime Sub System / Process (csrss.exe) or the Console Windows Host (conhost.exe), which provide the window when you run console applications.
Also, if the screenshot is not missleading, it looks like the superflous characters (especially visible for the closing parenthesis from "problem 6") are not even fully repeated, but only partial. I.e. the character is somehow "cut".
Anyway, there are some steps you could try to further investigage the problem:
Does it only happen on your system?
Does it only happen with 64bit processes (I assume your having one from the CMD title)
Does it also happen if you're not actually throwing the exception, e.g.
std::logic_error err("blah");
std::cout << err.what() << std::endl;
Can you change your program to use stdio instead of iostreams? And does it still happen then.
Try to redirect the output of the program to a file (e.g. "myapp.exe > foo.txt"). Does the file also contain the extra "!".
I have seen such a behavior under totally different circumstances.
Example:
printf("12345678901234567890\r"); /* carriage return, but no linefeed */
printf("ABCDEFGHIJ\n");
This should output:
ABCDEFGHIJ1234567890
But then, I don't see anything like that (iostreams vs. stdio or not) in your code.
It worries me that you catch 'exception &' instead of 'const exception &'. 'ex' might actually refere to an object that has already been destroyed, so the what() method returns garbage. You must ensure that the 'ex' parameter in your catch-handler, referes to a valid copy of the object originally thrown.