Can a call to free()
fail in any way?
For example:
free(NULL);
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 byptr
to be deallocated, that is, made available for further allocation. Ifptr
is a null pointer, no action occurs. Otherwise, if the argument does not match a pointer earlier returned by thecalloc
,malloc
, orrealloc
function, or if the space has been deallocated by a call tofree
orrealloc
, the behavior is undefined.The
free
function returns no value.