checking for NULL before calling free

zaharpopov picture zaharpopov · Dec 16, 2009 · Viewed 12.9k times · Source

Many C code freeing pointers calls:

if (p)
  free(p);

But why? I thought C standard say the free function doesn't do anything given a NULL pointer. So why another explicit check?

Answer

anon picture anon · Dec 16, 2009

The construct:

free(NULL);

has always been OK in C, back to the original UNIX compiler written by Dennis Ritchie. Pre-standardisation, some poor compilers might not have fielded it correctly, but these days any compiler that does not cannot legitimately call itself a compiler for the C language. Using it typically leads to clearer, more maintainable code.