我的代码:
#include<stdio.h>
#include<stdlib.h>
#include<cs50.h>
int main(void)
{
char *name = malloc(50 * sizeof(char));
if(!name)
{
printf("Memory allocation problem.\n");
return 1;
}
name = get_string("Enter your name: ");
printf("Hello, %s\n", name);
free(name);
}
输出:
Enter your name: dog
Hello, dog
*** Error in `malloc0': double free or corruption (fasttop): 0x0000000001084050 ***
我无法理解我哪里错了这是一个非常简单的代码,用于输入名称并打印它,但名称存储在堆内存中。
我只执行了一次 free()
但为什么会出现两次 free 错误??
有人请帮助我理解这个问题。
最佳答案
cs50 自动管理自己的内存。
在 main 之前,libcs50 在 cs.50:449 中注册 atexit
回调:
/**
* Called automatically before execution enters main.
*/
INITIALIZER(setup)
{
// Disable buffering for standard output
setvbuf(stdout, NULL, _IONBF, 0);
atexit(teardown);
}
teardown()
函数释放所有由 libcs50 分配的内存:
static void teardown(void)
{
// Free library's strings
if (strings != NULL)
{
for (size_t i = 0; i < allocations; i++)
{
free(strings[i]);
}
free(strings);
}
}
其中 strings
是 cs50.c:67 中的全局对象.
当您free(name)
时,名称后面的指针也存储在strings[0]
中(分配为in get_string()
)。
在 main()
退出后,执行 atexit
注册回调,并执行 free(strings[0])
尝试双重释放对象。
关于c - 在只编写一个自由函数的情况下获得双重自由,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54073405/