C语言 munmap_chunk(): 无效指针
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/32118545/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
munmap_chunk(): invalid pointer
提问by delabania
I've spotted the error in my program and decided to write a simple one, which would help me understand what's going on. Here it is :
我发现了我的程序中的错误,并决定编写一个简单的程序,这将有助于我了解发生了什么。这里是 :
#include <stdio.h>
#include <stdlib.h>
char * first()
{
char * word = malloc(sizeof(char) * 10);
word[0] = 'a';
word[1] = 'b';
word[2] = 'strcpy(word, "ab");
';
return word;
}
char * second ()
{
char * word = malloc(sizeof(char) * 10);
word = "ab";
return word;
}
int main ()
{
char * out = first();
printf("%s", out);
free(out);
out = second();
printf("%s", out);
free(out);
return 0;
}
The first()function is working properly, but the second()(exactly the free(out)) genarates error:
该first()函数工作正常,但second()(正是free(out))产生错误:
Error in `./a.out': munmap_chunk(): invalid pointer: 0x0000000000400714 *** ababAborted (core dumped)
`./a.out' 中的错误:munmap_chunk():无效指针:0x0000000000400714 *** ababAborted (core dumped)
I don't understand why the first function is correct, but the second isn't. Could anyone explain why?
我不明白为什么第一个函数是正确的,但第二个不是。谁能解释一下为什么?
回答by fuz
In the function second(), the assignment word = "ab";assigns a new pointer to word, overwriting the pointer obtained through malloc(). When you call free()on the pointer later on, the program crashes because you pass a pointer to free()that has not been obtained through malloc().
在函数中second(),赋值word = "ab";给 分配了一个新指针word,覆盖了通过 获得的指针malloc()。当您free()稍后调用该指针时,程序会崩溃,因为您传递了一个free()尚未通过malloc().
Assigning string literals does not have the effect of copying their content as you might have thought. To copy the content of a string literal, use strcpy():
分配字符串文字不会像您想象的那样复制其内容。要复制字符串文字的内容,请使用strcpy():
char * word = malloc(sizeof(char) * 10);
word = "ab";
回答by ameyCU
In function char * second
在功能上 char * second
The second statement word = "ab";changes wordto point away from the allocated memory.You are not copying the string "ab"to the area of heap allocated by malloc.
第二个语句word = "ab";更改word为指向远离分配的内存。您没有将字符串复制"ab"到由 分配的堆区域malloc。
And to freea memory that is not allocated by mallocor similar functions crashes your program.
并且free没有由malloc或类似功能分配的内存会使您的程序崩溃。
Attempting to free an invalid pointer (a pointer to a memory block that was not allocated by calloc, malloc, or realloc) may affect subsequent allocation requests and cause errors.
尝试释放无效指针(指向未由 calloc、malloc 或 realloc 分配的内存块的指针)可能会影响后续分配请求并导致错误。
You should use here strcpyas also suggested by others.
您也应该strcpy按照其他人的建议使用此处。

