2015-08-20 549 views
13

我在程序中发现了错误,并决定编写一个简单的错误代码,这会帮助我理解正在发生的事情。那就是:munmap_chunk():无效指针

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

char * first() 
{ 
    char * word = malloc(sizeof(char) * 10); 
    word[0] = 'a'; 
    word[1] = 'b'; 
    word[2] = '\0'; 
    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; 
} 

first()功能是否工作正常,但second()(完全free(out))genarates错误:

Error in `./a.out': munmap_chunk(): invalid pointer: 0x0000000000400714 *** ababAborted (core dumped)

我不明白为什么第一个功能是正确的,但第二不是。谁能解释为什么?

+2

您不能直接将字符串分配给char数组,请使用'strcpy(word,“ab”)'。 – gengisdave

回答

20

在函数second()中,赋值word = "ab";word分配一个新指针,覆盖通过malloc()获得的指针。当您稍后在指针上呼叫free()时,程序崩溃是因为您将指针传递给free(),该指针尚未通过malloc()获取。

分配字符串文字不会像您想象的那样复制其内容。要复制一个字符串的内容,请使用strcpy()

strcpy(word, "ab"); 
7

在funxtion char * second -

char * word = malloc(sizeof(char) * 10); 
word = "ab"; 

第二条语句word = "ab";改变word从分配memory.You点远没有抄袭字符串"ab"分配给由malloc分配的堆区域。

而对于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.

你也应该在这里使用strcpy也可以按其他人的建议使用。