在 c++ 中 int 数组周围堆栈损坏错误
Stack Corruption error around the int array in c++
我正在尝试编写一些 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。
相关文章:
- 将大双精度转换为无符号 int 期间堆栈损坏
- 程序终止时堆栈损坏?
- 为什么我的visual c++在堆栈损坏的情况下没有触发堆栈损坏错误
- 调试堆栈损坏问题
- 如何在退出时修复OpenGL堆栈损坏
- OpenCV C++:声明一个新变量会导致堆栈损坏
- 使用 sscanf 堆栈损坏
- C#到C代码P/调用多个std:字符串声明导致堆栈损坏
- 填充数组会导致数组周围的堆栈损坏
- 试图计算fibonacci(n)的变量“f”周围的堆栈损坏
- C++-如何在程序退出时找到堆/堆栈损坏的源
- 链表实现的堆栈损坏
- 可视化C++映射迭代和堆栈损坏
- 在 c++ 中 int 数组周围堆栈损坏错误
- 测试《毁灭战士3》堆栈实现时堆栈损坏
- 如何知道析构函数中的堆栈损坏来自何处
- 在c++中添加int数组时,试图找出堆栈损坏的问题
- 用错误的“”调用构造函数;这个“;指针.这是堆栈损坏吗
- GetCPUDescriptorHandleForHeapStart堆栈损坏
- memcpy之后堆栈损坏