gpt4 book ai didi

c - 堆损坏检测到 C 中的内存泄漏

转载 作者:太空宇宙 更新时间:2023-11-04 05:49:06 24 4
gpt4 key购买 nike

我得到了错误提示

Debug assertation failed and heat corruption detected

好像我的程序中的一切都运行良好,但我收到了那个错误。这里的内存泄漏在哪里?我必须释放 main 中的内存,因为我的函数需要返回指针。

我的代码:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int *dynamic_reader(unsigned int n) {

/*making new array and checking if allocation succeeded*/
int *mem;
mem = malloc(n * sizeof(int));
if (!mem) {
printf("Memory allocation failed\n");
exit(-1);
}

/*letting the user to input the values for the array*/
int i = 0;
while (i < n) {
scanf("\n%d", &mem[i]);
i++;
}

/*printing the array just to make sure everything is good*/
for (int j = 0; j < n; j++) {
printf("%d ", mem[j]);
}

return mem;
}
int *insert_into_array(int *arr, unsigned int num, int newval) {

/*making new bigger array*/
int *newarr = realloc(arr, (num + 1) * sizeof(int));

/*adding the integer to this new array */
newarr[num] = newval;
printf("\n");

/*printing to make sure everything is correct*/
for (int j = 0; j < num + 1; j++) {
printf("%d ", newarr[j]);
}
return newarr;
}
int main(void) {
/*In dynamic_reader function I need to make an array which size is given as a parameter*/
/*In this case I choosed 3*/
int *arr = dynamic_reader(3);
int num = 3;
/*In insert_into_array function I need to add one integer to this array I made in dynamic_reader*/
/*The parameters are the array, the number of elements in the array already done and the integer I want to add*/
int *c = insert_into_array(arr, num, 9);

/*I free the memory here because I need to return the pointers of these arrays in the function so it cant be done there*/
free(arr);
free(c);
}

最佳答案

你正在双重释放你的内存。查看 realloc 的文档. Realloc 将 1) 扩展传递的缓冲区或 2) 分配一个新缓冲区、复制数据并释放原始缓冲区。当你这样做时:

free(arr);
free(c);

您正在双重释放一个已经被 realloc 释放或已经被第一个 free(arr)

释放的值

此外,您应该检查 realloc 是否失败(返回 NULL),如果失败,请适当处理。

关于c - 堆损坏检测到 C 中的内存泄漏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48916133/

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