gpt4 book ai didi

c - C 中的 munmap_chunk 错误

转载 作者:太空宇宙 更新时间:2023-11-04 03:40:19 32 4
gpt4 key购买 nike

我一直在试验动态内存分配,并且遇到了 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/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com