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

CPointersMemory Management

C Problem Overview


> 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?

C Solutions


Solution 1 - C

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.

Solution 2 - C

It is good practice to not bother checking for NULL before calling free. Checking just adds unnecessary clutter to your code, and free(NULL) is guaranteed to be safe. From section 7.20.3.2/2 of the C99 standard:

> 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.

As noted in the comments, some people sometimes wonder if checking for NULL is more efficient than making a possibly unnecessary function call. However, this:

  • Is a premature micro-optimization.
  • Shouldn't matter. Checking for NULL first even might be a pessimization. For example, if 99% of the time your pointers aren't NULL, then there would be a redundant NULL check 99% of the time to avoid an extra function call 1% of the time.

Solution 3 - C

See http://linux.die.net/man/3/free which states:

> If ptr is NULL, no operation is performed.

Solution 4 - C

In my opinion, no, at least not in your case.

If you couldn't allocate memory, you should have checked that WAY before the call of free.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionridView Question on Stackoverflow
Solution 1 - CorlpView Answer on Stackoverflow
Solution 2 - CjamesdlinView Answer on Stackoverflow
Solution 3 - CHello71View Answer on Stackoverflow
Solution 4 - CGeorgeView Answer on Stackoverflow