. Advertisement .
..3..
. Advertisement .
..4..
As the title says, I am getting the “munmap_chunk(): invalid pointer” error. How can I fix it so the error goes away? Here is my detail:
#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;
}
When I operated it and I received the error text:
Error in `./a.out': munmap_chunk(): invalid pointer: 0x0000000000400714 ***
ababAborted (core dumped)
I appreciate any help from you.
The cause: 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(). Therefore, assigning string literals does not have the effect of copying their content.
Solution: Let’s use
strcpy()
to copy the string literal’s content.Function
char * second
The
word = "ab";
second statement changesword
to point away to the allocated memory. You are not copying"ab"
to an area of heap thatmalloc
has allocated.To
free
, a memory not allocated bymalloc
and similar functions crashes your program.As suggested by others, you should use
strcpy
.