Can a call to free() in C ever fail?

Taichman picture Taichman · Mar 15, 2011 · Viewed 12.7k times · Source

Can a call to free() fail in any way?

For example:

free(NULL);

Answer

E.Benoît picture E.Benoît · Mar 15, 2011

Freeing a NULL pointer cannot fail. And free doesn't return any error, but freeing unallocated memory, already freed memory or the middle of an allocated block is undefined behaviour - it may cause a memory error and the program may abort (or worse, it will corrupt the heap structure and crash later).

Or, even worse than that, keep running but totally corrupt your data and write it to disk without you realising :-)

The relevant portion of the standard (C99) is section 7.20.3.2:

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

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. Otherwise, if the argument does not match a pointer earlier returned by the calloc, malloc, or realloc function, or if the space has been deallocated by a call to free or realloc, the behavior is undefined.

The free function returns no value.