Search code examples
cmemory-leaksdynamic-memory-allocationundefined-behavior

C Allocating Memory in Loop: Error munmap_chunk(): invalid pointer


I wrote a little test code that allocates memory and just seeing the result on valgrind when I free the pNumber variable.

#include <stdlib.h>

int *pNumber = NULL;
static int s_array[10] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};

int main() {
    for(int i = 0; i < 10; i++) {
        pNumber = (int*) malloc(100);
        pNumber = &s_array[i];
    }
    free(pNumber);
    pNumber = NULL;
    
    return 0;
}

However I get the error of "munmap_chunk(): invalid pointer", particularly the pNumber = &s_array[i] causes the error. However, when I change it to *pNumber = s_array[i], the invalid pointer error is gone.

 for(int i = 0; i < 10; i++) {
        pNumber = (int*) malloc(100);
        *pNumber = s_array[i];
    }

I'm just curious why pNumber = &s_array[i] would cause that error?

I thought I am freeing the pointer that has been allocated with malloc?


Solution

  • In the first case the program has undefined behavior.

    You are trying to free memory that you did not allocate.

    free(pNumber);
    

    because the pointer pNumber points to memory with the static storage duration.

    pNumber = &s_array[i];
    

    As for this statement

    *pNumber = s_array[i];
    

    then it sets the object pointed to by pNumber by the value of the expression s_array[i] and the pointer itself was not reassigned. It points to the dynamically allocated memory. So you may use the pointer to free the allocated memory.

    That is in the first case you are reassigning the pointer itself loosing the address of the dynamically allocated memory and trying to free an object with the static storage duration. As a result there are memory leaks and undefined behavior.

    In the second case you just set a value to the allocated memory. So the program only produces numerous memory leaks.