gpt4 book ai didi

c++ - 检测到堆损坏 : after Normal block (#126)

转载 作者:行者123 更新时间:2023-11-30 03:00:56 25 4
gpt4 key购买 nike

我这辈子都弄不明白为什么会出现这个调试错误:

检测到堆损坏:在正常 block (#126)之后0x004cF6c0CRT 检测到应用程序在堆错误结束后写入内存。

据我了解,无论何时使用 new 运算符都需要释放内存,我做了,但我仍然遇到问题。

由于某种原因,程序在递归函数中没有正确结束。我对其进行了调试,并通过断点遍历了每一行代码。

在 countSum 中的 if 语句的末尾,它以某种方式从 i 中减去 1然后重新进入 if block ......这是不应该做的。

为什么会这样?

/*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
}
}

最佳答案

array为单个 int 保留足够的空间:

int *array = new int;

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

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

然后接受size数量int秒。使用 delete[]当你使用 new[] .

关于c++ - 检测到堆损坏 : after Normal block (#126),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11569473/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com