Can a call to free()
fail in any way?
For example:
free(NULL);
free() just declares, to the language implementation or operating system, that the memory is no longer required. When it is written over is not defined behavior.
The free() function in C++ deallocates a block of memory previously allocated using calloc, malloc or realloc functions, making it available for further allocations. The free() function does not change the value of the pointer, that is it still points to the same memory location.
The C Standard specifies that free(NULL) has no effect: The free function causes the space pointed to by ptr to be deallocated, that is, made available for further allocation.
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.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With