Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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

For example:

free(NULL); 
like image 700
Taichman Avatar asked Mar 15 '11 07:03

Taichman


People also ask

What happens when you free () in C?

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.

What does the function free () do?

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.

What happens if you free null in C?

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.


2 Answers

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.

like image 96
E.Benoît Avatar answered Oct 27 '22 00:10

E.Benoît


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

like image 42
Gabe Avatar answered Oct 26 '22 23:10

Gabe