【发布时间】:2017-07-16 05:14:02
【问题描述】:
我写了以下程序:
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
char *s;
s = (char*)malloc(15);
s = "Hello World";
printf("%s",s);
free(s);
return 0;
}
没有编译错误。 我收到此运行时错误: * `./s' 中的错误:munmap_chunk():无效指针:0x0000000000400694 * 你好世界中止
为什么会出现此运行时错误,我该如何解决?
是不是因为在调用malloc之后,s收到了某个地址,赋值s = "Hello World"修改了s的地址,但是后来在做free(s)的时候,指向free的指针不是malloc返回的那个吗?
【问题讨论】:
-
你的解释是正确的。
-
顺便说一句,没有必要在 C 中强制转换
void-pointers。 -
好的,谢谢@alk
-
这能回答你的问题吗? munmap_chunk(): invalid pointer
标签: c string dynamic-memory-allocation