c - 在只编写一个免费功能的情况下获得双重免费
问题描述
我的代码:
#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()
一次,但为什么双重免费错误?
有人请帮我理解这个问题。
解决方案
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);
}
}
cs50.c:67strings
中的全局对象在哪里。
当您free(name)
名称后面的指针也存储在strings[0]
(分配在get_string()
)中。
main()
退出后,atexit
注册的回调被执行,并free(strings[0])
尝试双重释放对象。
推荐阅读
- python - 根据单独的值与不同数据框的关系更改数据框中的值
- c - 在 C 中发送信号?
- python - python中最长的等数序列
- python - Python函数参数和参数
- spss - SPSS 未运行
- html - 为什么这个按钮在 Firefox 中的对齐方式不同?
- android - Koin 上下文隔离:正确设置并避免随机 NoBeanDefFoundException
- julia - 使用 Julia 模拟布朗运动的插值
- python - 如何正确修复丢失的 python.app?
- android-jetpack-compose - 禁用 BottomNavigationItem 的涟漪效应