我不能为我的生活弄清楚为什么我收到此调试错误:在 0x004cF6c0 普通块(#126)后:堆损坏检测:普通块(#126)后
堆损坏检测CRT检测到应用程序在堆填充程序结束后写入内存。
我知道你需要释放内存,每当你使用新的操作符, 我做了,我仍然遇到问题。
由于某种原因程序在递归函数中没有正确结束。我调试了它,并用断点遍历了每行代码。
在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
}
}
我认为创建动态数组的全部意义在于让您可以添加更多内容。我从来没有将数组声明为const int数组[0] – user1066524 2012-07-19 21:23:59
这意味着编译时不需要知道大小,但它不会自动增长:一个'std :: vector'会。 –
hmjd
2012-07-19 21:24:52
是的我知道载体更好。我的老师当然要求一个数组......尽管数组在数据方面令人难以置信地令人讨厌并且没有什么帮助。 – user1066524 2012-07-19 21:28:46