munmap_chunk(): invalid pointer

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");

In function char * second

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

The second statement word = "ab"; changes word to point away from the allocated memory.You are not copying the string "ab" to the area of heap allocated by malloc.

And to free a memory that is not allocated by malloc or similar functions crashes your program.

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.

You should use here strcpy as also suggested by others.

Tags:

C