小编del*_*nia的帖子

munmap_chunk():指针无效

我在我的程序中发现了错误并决定编写一个简单的错误,这将有助于我了解正在发生的事情.这里是 :

#include <stdio.h>
#include <stdlib.h>

char * first()
{
    char * word = malloc(sizeof(char) * 10);
    word[0] = 'a';
    word[1] = 'b';
    word[2] = '\0';
    return word;
}

char * second ()
{
    char * word = malloc(sizeof(char) * 10);
    word = "ab";
    return word;
}

int main ()
{
    char * out = first();
    printf("%s", out);
    free(out);
    out = second();
    printf("%s", out);
    free(out);
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

first()功能正常工作,但second()(确切地说free(out))发生了错误:

`.a.out'出错:munmap_chunk():无效指针:0x0000000000400714***ababAborted(核心转储)

我不明白为什么第一个功能是正确的,但第二个功能不正确.谁有人解释为什么?

c

26
推荐指数
2
解决办法
5万
查看次数

标签 统计

c ×1