Is it good practice to free a NULL pointer in C?

rid picture rid · May 21, 2011 · Viewed 74.2k times · Source

Possible Duplicate:
Does free(ptr) where ptr is NULL corrupt memory?

I'm writing a C function that frees a pointer if it was malloc()ed. The pointer can either be NULL (in the case that an error occured and the code didn't get the chance to allocate anything) or allocated with malloc(). Is it safe to use free(ptr); instead of if (ptr != NULL) free(ptr);?

gcc doesn't complain at all, even with -Wall -Wextra -ansi -pedantic, but is it good practice?

Answer

orlp picture orlp · May 21, 2011

Quoting the C standard, 7.20.3.2/2 from ISO-IEC 9899:

void free(void *ptr);

If ptr is a null pointer, no action occurs.

Don't check for NULL, it only adds more dummy code to read and is thus a bad practice.


However, you must always check for NULL pointers when using malloc & co. In that case NULL mean that something went wrong, most likely that no memory was available.