在 c++ 中 int 数组周围堆栈损坏错误

Stack Corruption error around the int array in c++

本文关键字:堆栈 损坏 错误 周围 数组 c++ int      更新时间:2023-10-16

我正在尝试编写一些 c++ 代码,该代码是公式的演示,但使用递归。这是我的程序及其引发的错误。

环境 - Visual Studio 2012
编译 - 成功
运行时异常 -
运行时检查失败 #2 - 变量"inputNumbers"周围的堆栈已损坏。

法典-

#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;        
    }
}

整个程序按照我期望的逻辑完美运行,并在调试时给出正确的输出,但在执行完成后退出 main(( 时抛出异常。
我看到我正在做一个非常愚蠢但复杂的内存管理错误[并且找不到它]。
任何帮助,不胜感激。

你不是在这里填充数组大小的两倍吗?

for (int i = 1; i < 51; i++)
{
    inputNumbers[cnt] = i;
    cnt++;
    inputNumbers[cnt] = i;
    cnt++;
}

对于长度为 50 的数组,您不能访问元素 49 以外的数组;因此代码应如下所示:

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++;
}

事实上,与前面的答案一样,您可能只想增加一次 cnt。