Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/assembly/6.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C 获取只有一个空闲函数的双空闲函数_C_Cs50 - Fatal编程技术网

C 获取只有一个空闲函数的双空闲函数

C 获取只有一个空闲函数的双空闲函数,c,cs50,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_st

我的代码:

#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);
}
我无法理解我错在哪里这是一个非常简单的代码,以获取名称并打印它,但名称存储在堆内存中。 我只是执行了一次免费,但为什么双重免费错误


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

cs50自动管理自己的内存

在main之前,libcs50在以下位置注册atexit回调:

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);
    }
}
其中字符串是中的全局对象

使用freename时,名称后面的指针也存储在指定的字符串[0]中


在主退出之后,执行atexit注册回调,并执行freestrings[0],它试图双重释放对象。

从get\u string的描述中:

提示用户从标准输入中输入一行文本,并将其作为字符串char*返回,无尾随行结尾。支持CR\r、LF\n和CRLF\r\n作为行尾。在堆上存储字符串,但库的析构函数在程序退出时释放内存。提示的格式类似于printf3


因此,正如您所看到的,它还可以在退出时将其从堆中释放出来。

我投票将此问题视为离题,因为它更适合于打开。您正在丢弃malloc返回的指针。1您调用malloc并将结果分配给name 2您调用get_string并将结果分配给name,丢失了旧的POINTER3您试图释放返回的get_字符串,该字符串可能不是来自malloc。@Ctx-这个问题是关于cs50的工作,整个SE站点都存在该问题,并且应该在哪里提出有关的问题。这是非常恰当的。@StoryTeller这个问题也可能是关于主题的,也许它更适合,但它肯定不是偏离主题的@Ctx-那就不要投赞成票。不管你同意与否,我都会投我认为合适的票。
/**
 * Called automatically before execution enters main.
 */
INITIALIZER(setup)
{
    // Disable buffering for standard output
    setvbuf(stdout, NULL, _IONBF, 0);
    atexit(teardown);
}
static void teardown(void)
{
    // Free library's strings
    if (strings != NULL)
    {
        for (size_t i = 0; i < allocations; i++)
        {
            free(strings[i]);
        }
        free(strings);
    }
}