【问题标题】:Stack Corruption error around the int array in c++C++中int数组周围的堆栈损坏错误
【发布时间】:2015-02-02 19:18:55
【问题描述】:

我正在尝试编写一些 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() 时抛出异常。
我看到我在做一个非常愚蠢但错综复杂的内存管理错误[并且找不到它]。
任何帮助表示赞赏。

【问题讨论】:

  • C++ 中的数组是零索引的

标签: c++ memory-management stack


【解决方案1】:

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

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

【讨论】:

  • 请拿枪射我的头……! ://
【解决方案2】:

对于长度为 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。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-08
    • 2013-07-28
    • 2012-11-05
    • 1970-01-01
    • 2014-12-11
    相关资源
    最近更新 更多