c - 为什么我会收到此错误以及如何修复它 : munmap_chunk(): invalid pointer: 0x0000000000400694 *** Hello WorldAborted

标签 c string dynamic-memory-allocation

我写了下面的程序:

#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 的返回地址(内存泄漏)

free()

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");

另外,看看 Do I cast the result of malloc?

关于c - 为什么我会收到此错误以及如何修复它 : munmap_chunk(): invalid pointer: 0x0000000000400694 *** Hello WorldAborted,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42454438/

相关文章:

c - 我的程序中的 scanfs 和/或 ifs 有问题(咖啡店)

c - 如何将多维 C 数组传递给函数?

c++ - 连接两个字符串文字

c++ - 指针后括号的含义

python - 使用 free() 时出现无效指针错误

c - POSIX和C语言有什么关系?

c++ - 交叉编译 GCC : Link tests are not allowed after GCC_NO_EXECUTABLES when checking dynamic linker characteristics

python - 从字符串中取出一个 Unicode 字符并对其进行解码

r - 在列表列表中查找/查找字符串,然后返回列表的名称

c++ - 动态创建指针数组