munmap_chunk(): invalid pointer

c
125,047

Solution 1

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

Solution 2

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.

Share:
125,047
Admin
Author by

Admin

Updated on July 14, 2022

Comments

  • Admin
    Admin 5 months

    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?

  • SatKetchum
    SatKetchum over 1 year
    But what exactly is munmap_chunk() mean? Can it just not be segfault ( as pointer passed to free is not wrt to malloc() ). And what are the other scenarios where the munmap_chunk() invalid pointer issue would arise?
  • fuz
    fuz over 1 year
    @SathvikSat munmap_chunk() is an internal function of the libc's memory management routine. This error message means that by writing into memory that does not belong to an object (but belongs to your process so no segfault), you corrupted internal data structures belonging to these routines. Trying to use these corrupted data structures, the internal routines crash.