首页 > 解决方案 > 在只编写一个免费功能的情况下获得双重免费

问题描述

我的代码:

#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()一次,但为什么双重免费错误?

有人请帮我理解这个问题。

标签: ccs50

解决方案


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);
    }
}

cs50.c:67strings中的全局对象在哪里。

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

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


推荐阅读