检测到堆损坏:在正常块之后(#126)

use*_*524 3 c++ memory heap-memory heap-corruption

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

检测到堆损坏:在 0x004cF6c0 处的正常块 (#126) 之后,CRT 检测到应用程序在堆 bugger 结束后写入内存。

我知道每当使用 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
    }
}
Run Code Online (Sandbox Code Playgroud)

hmj*_*mjd 5

array拥有足够的空间容纳单个int

int *array = new int;
Run Code Online (Sandbox Code Playgroud)

但可能会尝试插入多个int,这会导致写入不可用的内存。要么使用 a std::vector<int>,要么必须事先知道分配int之前输入的 s的最大数量。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];
}
Run Code Online (Sandbox Code Playgroud)

然后接受ssize的数量intdelete[]使用时使用new[]

  • 这意味着不需要在编译时知道大小,但它不会自动增长:`std::vector&lt;int&gt;` 会自动增长。 (2认同)