我在程序中发现了错误,并决定编写一个简单的错误代码,这会帮助我理解正在发生的事情。那就是: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;
}
的first()
功能是否工作正常,但second()
(完全free(out)
)genarates错误:
Error in `./a.out': munmap_chunk(): invalid pointer: 0x0000000000400714 *** ababAborted (core dumped)
我不明白为什么第一个功能是正确的,但第二不是。谁能解释为什么?
您不能直接将字符串分配给char数组,请使用'strcpy(word,“ab”)'。 – gengisdave