Search code examples
c++cmemory-managementmemory-leaksfree

Why doesn't free(p) set p to NULL?


Any reasons why this can not be standard behavior of free()?

multiple pointers pointing to the same object:

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

void safefree(void*& p)
{
    free(p); p = NULL;
}

int main()
{
    int *p = (int *)malloc(sizeof(int));
    *p = 1234;
    int*& p2 = p;
    printf("p=%p p2=%p\n", p, p2);
    safefree((void*&)p2);
    printf("p=%p p2=%p\n", p, p2);
    safefree((void*&)p); // safe

    return 0;
}

assignment from malloc demands cast from void*

vice versa:

safefree() demands cast to void*& (reference)


Solution

  • If it did, you would have to pass a pointer to a pointer to the function:

    int * p = malloc( sizeof( int ));
    free( & p );
    

    which I'm sure many people would get wrong.