我一生都无法弄清楚为什么会出现此调试错误:
检测到堆损坏:在 0x004cF6c0 CRT 的正常块 (#126) 后检测到应用程序在堆错误结束后写入内存。
我知道每当您使用 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
}
}