Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

munmap_chunk(): invalid pointer

Tags:

c

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] = '\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; } 

The first() function is working properly, but the second() (exactly the free(out) ) genarates error:

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

I don't understand why the first function is correct, but the second isn't. Could anyone explain why?

like image 209
delabania Avatar asked Aug 20 '15 12:08

delabania


People also ask

What is Munmap_chunk () invalid pointer?

Memory error: "munmap_chunk: invalid pointer"This happens when the pointer passed to (C-library language routine free(), which is called from Fortran routine NULLIFY()) is not valid or has been modified somehow.

What does free () invalid pointer mean?

You're trying to free memory that's not heap memory. Don't do that. You're trying to free the inside of a block of memory. When you have in fact allocated a block of memory, you can only free it from the pointer returned by malloc . That is to say, only from the beginning of the block.

What is an invalid pointer?

An invalid pointer reference occurs when a pointer's value is referenced even though the pointer doesn't point to a valid block. One way to create this error is to say p=q;, when q is uninitialized. The pointer p will then become uninitialized as well, and any reference to *p is an invalid pointer reference.


1 Answers

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().

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(word, "ab"); 
like image 90
fuz Avatar answered Oct 01 '22 13:10

fuz