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

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


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.


Simple answer: because you might be freeing an expression, e.g. free(find_named_object("foo")).

In more detail: The free function takes a void* parameter, which is the address of the memory to free. This doesn't confer to the function any knowledge of the original variable that supplied the address (or, for that matter, whether there even exists a variable). Just setting the parameter passed in to NULL would do nothing either, since it's just a local copy of the address.


Bjarne Stroustrup discussing whether the delete operator should zero its operand. It's not the free() function, but it's a good discussion anyway. Consider points like:

  • What would be zeroed out if you said free(p + 1)?
  • What if there are two pointers to the memory? Why only set one to null if a dangling reference is still left behind?

He also says it was intended but never happened with operator delete:

C++ explicitly allows an implementation of delete to zero out an lvalue operand, and I had hoped that implementations would do that, but that idea doesn't seem to have become popular with implementers.