c - 在只编写一个自由函数的情况下获得双重自由

标签 c cs50

我的代码:

#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 之前,libcs​​50 在 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() 函数释放所有由 libcs​​50 分配的内存:

static void teardown(void)
{
    // Free library's strings
    if (strings != NULL)
    {
        for (size_t i = 0; i < allocations; i++)
        {
            free(strings[i]);
        }
        free(strings);
    }
}

其中 stringscs50.c:67 中的全局对象.

当您free(name) 时,名称后面的指针也存储在strings[0] 中(分配为in get_string())。

main() 退出后,执行 atexit 注册回调,并执行 free(strings[0]) 尝试双重释放对象。

关于c - 在只编写一个自由函数的情况下获得双重自由,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54073405/

相关文章:

尝试遍历共享库的符号表时导致 C 指针分段

c - 在 C 中实现拼写检查器 : Valgrind reports memory errors

c - 从c中的fread()形式读取缓冲区数据

c - fread() 不添加空终止符 [C],无法添加 1,因为我有一个指向指针的指针

c - 井字游戏玩家 vs 人工智能——人工智能问题

c - 进程调用 ptrace(PTRACE_TRACEME, ...) 后会发生什么?

c - 指向未知长度字符串的指针数组

C - 舍入问题 (CS50)

cs50 pset1 贪婪异常错误

CS50 - 信用卡分配;分段故障