2

我一生都无法弄清楚为什么会出现此调试错误:

检测到堆损坏:在 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
    }
}
4

2 回答 2

4

array为单人提供足够的空间int

int *array = new int;

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

如果这是一个学习练习并且您不想使用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];
}

然后接受s 的size数量int。使用delete[]时使用new[]

于 2012-07-19T21:22:21.580 回答
0

解决方案是设置大小 new int[size]....虽然我希望如果它是动态的,您不必设置大小。

于 2012-07-19T21:41:19.923 回答