Can a call to free()
fail in any way?
For example:
free(NULL);
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.
Unless you invoke undefined behavior (like "double-free" or try to free()
a string literal) free()
can't fail.
free(NULL)
does nothing; free
on a pointer that wasn't allocated with the same allocator (malloc
, calloc
, etc.) or was already freed is undefined. Since free
returns void
, the only way it can fail is by crashing (e.g. segfault).
Yes it can fail in multiple situations. E.g.
free(NULL);
Calling free() with a null pointer is permitted and will not cause an error - See: free() - Opengroup
Calling free with a previously free'd pointer will usually cause a segment violation and your program to be terminated.
Depending on the implementation, free()
could fail if there is memory corruption, such as with this:
char *p = malloc(1000);
*(p-1)=7;
free(p);
Although that is a contrived example, similar things can happen by running off the end or start of an array. The first you may know of it is a protection fault in free()
.