我不能为我的生活弄清楚为什么我得到这个调试错误:
检测到堆腐蚀:正常阻止(#126)后 0x004cF6c0 CRT检测到应用程序在堆错误结束后写入内存。
据我所知,每当使用new运算符时都需要释放内存, 我做了,我仍然遇到问题。
由于某种原因,程序在递归函数中没有正确结束。 我调试了它并通过断点检查了每行代码。
在countSum中的if语句结束时,它以某种方式从i中减去1 然后重新进入if块.....它不应该这样做。
为什么会这样?
/*this program calculates the sum of all the numbers in the array*/
#include <iostream>
#include <time.h>
using namespace std;
/*prototype*/
void countSum(int, int, int, int*);
int main(){
bool flag;
int num;
int sum = 0, j=0;
int *array = new int;
do{
system("cls");
cout<<"Enter a number into an array: ";
cin>>array[j];
cout<<"add another?(y/n):";
char choice;
cin>>choice;
choice == 'y' ? flag = true : flag = false;
j++;
}while(flag);
int size = j;
countSum(sum, 0, size, array);
//free memory
delete array;
array = 0;
return 0;
}
void countSum(int sum, int i, int size, int *array){
if (i < size){
system("cls");
cout<<"The sum is :"<<endl;
sum += array[i];
cout<<"...."<<sum;
time_t start_time, stop_time;
time(&start_time);
do
{
time(&stop_time); //pause for 5 seconds
}
while((stop_time - start_time) < 5);
countSum(sum, (i+1) , size, array); //call recursive function
}
}
答案 0 :(得分:3)
array
为单个int
提供了足够的空间:
int *array = new int;
但是可能会尝试插入多个int
,这会导致写入无法使用的内存。要么使用std::vector<int>
,要么必须事先知道在分配int
之前输入的array
的最大数量。
如果这是一次学习练习,并且您不想使用std::vector<int>
,则可以提示用户输入他们想要输入的int
个数:
std::cout << "Enter number of integers to be entered: ";
int size = 0;
std::cin >> size;
if (size > 0)
{
array = new int[size];
}
然后接受size
个int
个。使用delete[]
时使用new[]
。
答案 1 :(得分:0)
解决方案是设置大小为new int [size] ....虽然我希望你不必设置大小,如果它是动态的。