Does free(ptr) where ptr is NULL corrupt memory?

7.20.3.2 The free function

Synopsis

#include <stdlib.h> 
void free(void *ptr); 

Description

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.

See ISO-IEC 9899.

That being said, when looking at different codebases in the wild, you'll notice people sometimes do:

if (ptr)
  free(ptr);

This is because some C runtimes (I for sure remember it was the case on PalmOS) would crash when freeing a NULL pointer.

But nowadays, I believe it's safe to assume free(NULL) is a nop as per instructed by the standard.


All standards compliant versions of the C library treat free(NULL) as a no-op.

That said, at one time there were some versions of free that would crash on free(NULL) which is why you may see some defensive programming techniques recommend:

if (ptr != NULL)
    free(ptr);

If ptr is NULL, no operation is performed.

says the documentation.