2012-07-19 95 views
1

我不能为我的生活弄清楚为什么我收到此调试错误:在 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 
    } 
} 

回答

3

array拥有足够的空间用于单个int

int *array = new int; 

,但有可能插入一个尝试多个int这将导致写入内存不可用。要么使用std::vector<int>,要么必须事先知道在分配array之前将要输入的最大数量int

如果这是一个学习的过程,你不希望使用std::vector<int>你可以提示用户输入他们希望进入的int S上的号码:

std::cout << "Enter number of integers to be entered: "; 
int size = 0; 
std::cin >> size; 
if (size > 0) 
{ 
    array = new int[size]; 
} 

然后接受sizeint秒。当您使用new[]时使用delete[]

+0

我认为创建动态数组的全部意义在于让您可以添加更多内容。我从来没有将数组声明为const int数组[0] – user1066524 2012-07-19 21:23:59

+2

这意味着编译时不需要知道大小,但它不会自动增长:一个'std :: vector '会。 – hmjd 2012-07-19 21:24:52

+0

是的我知道载体更好。我的老师当然要求一个数组......尽管数组在数据方面令人难以置信地令人讨厌并且没有什么帮助。 – user1066524 2012-07-19 21:28:46

0

解决的办法是设置尺寸new int [size] ....虽然我希望如果它是动态的,你不必设置大小。

+0

真正的解决方案是std :: vector – paulm 2014-10-15 12:36:17