Search code examples
cfree

free() : invalid pointer and how to reuse a currently freed pointer


I want to address my pointer to another object and free the memory of previous object. This is what I did but I had a invalid pointer error. What is the right way to do it?

#include <stdio.h>
#include <stdlib.h>

int main(int argc, char const *argv[])
{
    int number = 5;
    int number2 = 10;

    // Give memory manually 
    int *pointer2number = (int *) malloc(sizeof(int));
    pointer2number = &number;

    printf("Number is %i\n", number);       
    printf("Address of number is %p\n", pointer2number);

    // Free memory 
    free(pointer2number);
    pointer2number = (int *) malloc(sizeof(int));
    pointer2number = &number2;
    printf("New number is %i\n", *pointer2number);
    return 0;
}

Solution

  • int *pointer2number = (int *) malloc(sizeof(int));
    pointer2number = &number;
    

    You assign the address of number to the pointer pointer2number and with that replace the address of the allocated dynamic memory stored in pointer2number before.

    The same goes for the second attempt with number2.

    Any attempt to free() a memory not previously allocated by a memory-management function, invokes undefined behavior:

    "The free function causes the space pointed to by ptr to be deallocated, that is, made available for further allocation. If ptr is a null pointer, no action occurs. Otherwise, if the argument does not match a pointer earlier returned by a memory management function, or if the space has been deallocated by a call to free or realloc, the behavior is undefined."

    Source: ISO/IEC 9899:2018 (C18), Section 7.22.3.3/2

    And as side-effect, the previously allocated dynamic memory isn´t free()d with that too.

    Overthink the logic of your program!