c - C 中的 munmap_chunk 错误

标签 c memory

我一直在试验动态内存分配,并且遇到了 C 中的 munmap_chunk 错误。 这是我的代码。

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

void get_input(char **input) {
  *input = (char *) malloc (100);
  *input = "hello world";
}

int main() {
  char *input;
  get_input(&input);
  puts(input);
  free(input);
  return 0;
}

这是执行程序时 valgrind 显示的内容。

==4116== Memcheck, a memory error detector
==4116== Copyright (C) 2002-2013, and GNU GPL'd, by Julian Seward et al.
==4116== Using Valgrind-3.10.0.SVN and LibVEX; rerun with -h for copyright info
==4116== Command: ./a.out
==4116== 
hello world
==4116== Invalid free() / delete / delete[] / realloc()
==4116==    at 0x4C2BDEC: free (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==4116==    by 0x400615: main (in /home/mark/Documents/CS32/a.out)
==4116==  Address 0x4006a4 is not stack'd, malloc'd or (recently) free'd
==4116== 
==4116== 
==4116== HEAP SUMMARY:
==4116==     in use at exit: 100 bytes in 1 blocks
==4116==   total heap usage: 1 allocs, 1 frees, 100 bytes allocated
==4116== 
==4116== 100 bytes in 1 blocks are definitely lost in loss record 1 of 1
==4116==    at 0x4C2AB80: malloc (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==4116==    by 0x4005D2: get_input (in /home/mark/Documents/CS32/a.out)
==4116==    by 0x4005FD: main (in /home/mark/Documents/CS32/a.out)
==4116== 
==4116== LEAK SUMMARY:
==4116==    definitely lost: 100 bytes in 1 blocks
==4116==    indirectly lost: 0 bytes in 0 blocks
==4116==      possibly lost: 0 bytes in 0 blocks
==4116==    still reachable: 0 bytes in 0 blocks
==4116==         suppressed: 0 bytes in 0 blocks
==4116== 
==4116== For counts of detected and suppressed errors, rerun with: -v
==4116== ERROR SUMMARY: 2 errors from 2 contexts (suppressed: 0 from 0)

为什么 free() 函数的行为是这样的?另外,从 valgrind 日志来看,为什么我的 char *input 变量没有被 malloc() 分配?

最佳答案

可以这样赋值:

*input = "hello world"; /* Not modifiable */

但是,你不需要用malloc保留空间,"hello world"有他自己的地址(在一些“只读”段)和任何尝试修改字符串会导致未定义的行为,因此不允许您释放它。

如果你想要一个可修改的字符串:

void get_input(char **input) {
    char str[] = "hello world";

    *input = malloc(sizeof(str)); /* Don't cast malloc */
    if (*input == NULL) {
        perror("malloc");
        exit(EXIT_FAILURE);
    }
    strncpy(*input, str, sizeof(str));
}

void get_input(char **input) {
    *input = strdup("hello world");
}

请注意,strdup 不是标准的,但它可用于许多实现。

关于c - C 中的 munmap_chunk 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29207663/

相关文章:

memory - 用小内存在大图上进行广度优先搜索

Java:检查非堆内存使用情况

c - 为什么我可以使用数组索引访问其他变量?

Clang 链接器和 i686

c++ - 直方图对于暗图像不准确

CreateProcessA %appdata%

c++ - std::map 是否从其 const 引用创建对象的新非 const 拷贝

c - 写入二维数组时出现段错误

c++ - VS 2008 和 VS 2017 之间的 Visual C++ 内存管理变化

c - 如何在代码 .h 文件中组织声明和函数并包含以实现最佳代码重用