Search code examples
cpointersfree

Why does this sequence of pointer operations cause an error?


Why does the (admittedly esoteric) pointer manipulation below cause the following error:

*** Error in /home/ubuntu/workspace/Project 3/Debug/Project 3': double free or corruption (out): 0x00007fffffffd7c0 ***

    int *intPointer = malloc(sizeof(int));
    *intPointer = 1;
    int intArray[] = { *intPointer };
    int *intPointer2 = &intArray[0];
    free(intPointer2);

Solution

  • The value assigned to intPointer2 is a pointer to the first element in intArray. This array was allocated on the stack, so attempting to free it is undefined behavior.

    You can only free memory that was returned by malloc/realloc/calloc. The fact that the first (and only) element in this array contains a copy of the value pointed to by intPointer (not a copy of the value of intPointer) doesn't matter.

    Only calling free(intPointer) would work.