我写了下面的程序:
#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 * Hello WorldAborted
为什么会出现此运行时错误,我该如何解决?
是不是因为调用malloc
后,s
收到了某个地址,赋值s = "Hello World"
修改了的地址code>s
,但是当执行 free(s)
时,发送到 free
的指针不是 malloc 返回的指针
?
最佳答案
Is it because after the call to malloc, s received a certain address, and the assignment s = "Hello World" modifies the address of s, but then when doing free(s), the pointer that is sent to free is not the one that was returned by malloc?
是
s = (char*)malloc(15);
s = "Hello World";
您正在覆盖 malloc
的返回地址(内存泄漏)
if the argument does not match a pointer earlier returned by the calloc(), malloc(), posix_memalign(), realloc(), or strdup() function, or if the space has been deallocated by a call to free() or realloc(), the behavior is undefined.
将 s = "Hello World";
更改为 strcpy(s, "Hello world");
关于c - 为什么我会收到此错误以及如何修复它 : munmap_chunk(): invalid pointer: 0x0000000000400694 *** Hello WorldAborted,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42454438/