Reputation: 3
I am trying to write some c++ code that is a demo for a formula but using Recursion. Here is my program and the error it throws.
Environment - Visual Studio 2012
Compilation - Successful
Runtime Exception -
Run-Time Check Failure #2 - Stack around the variable 'inputNumbers' was corrupted.
Code -
#include <stdlib.h>
#include <iostream>
using namespace std;
int FindNumber(int Numbers[],int index,int sum, int count)
{
if(count == 0)
return sum;
else if (count == 1)
{
sum -= Numbers[index-1];
index = index -1;
count = count-1;
return sum = FindNumber(Numbers,index,sum,count);
}
else
{
sum += Numbers[index-1];
index = index -1;
count = count-1;
return sum = FindNumber(Numbers,index,sum,count);
}
}
void main()
{
int inputNumbers[50]; //declare the series of numbers
int cnt = 0; //define and initailize an index counter for inserting the values in number series.
int position = 7; //defines the position of the number in the series whose value we want to find.
// insert the number series values in the int array.
for (int i = 1; i < 51; i++)
{
inputNumbers[cnt] = i;
cnt++;
inputNumbers[cnt] = i;
cnt++;
}
cnt=0;
for (int i = 1; i < 51; i++)
{
cout<<inputNumbers[cnt]<<endl;
cnt++;
cout<<inputNumbers[cnt]<<endl;
cnt++;
}
// set another counter variable to 3 since formula suggests that we need to substrat 3 times from the nth position
// Formula : nth = (n-1)th + (n-2)th - (n-3)th
cnt = 3;
int FoundNumber = 0;
//Check if position to be found is greater than 3.
if(position>3)
{
FoundNumber = FindNumber(inputNumbers,position,FoundNumber,cnt);
cout<< "The number found is : " << FoundNumber<< endl;
}
else
{
cout<<"This program is only applicable for finding numbers of a position value greater than 3..."<<endl;
}
}
The entire program is working perfect as per the logic I expect and gives proper output when i debug it but throw exception while exiting the main() after execution is complete.
I see i am doing a really silly but an intricate memory management mistake[and cannot find it].
Any help is appreciated.
Upvotes: 0
Views: 175
Reputation: 1093
For an array of length 50 you cannot access beyond element 49; so code should be like:
int inputNumbers[50]; //declare the series of numbers
int cnt = 0; //define and initailize an index counter for inserting the values in number series.
// insert the number series values in the int array.
for (int i = 0; i < 50; i++)
{
inputNumbers[cnt] = i;
cnt++;
}
And indeed as in the previous answer you probably want to increment cnt only once.
Upvotes: 1
Reputation: 20130
Aren't you filling twice the size of the array here?
for (int i = 1; i < 51; i++)
{
inputNumbers[cnt] = i;
cnt++;
inputNumbers[cnt] = i;
cnt++;
}
Upvotes: 3