C Reference ยท stdlib.h
C free() function
Reference for C free(): release memory from malloc, calloc or realloc, why free(NULL) is safe, double free and dangling pointers, and nulling after free.
free() gives a block of heap memory back to the allocator so it can be reused. You may pass it only a pointer that was returned by malloc(), calloc(), realloc() or aligned_alloc() (or NULL), and only once.
After free(p) the pointer p still holds the old address, but the memory it points to is no longer yours. Using it is a use after free, one of the most common causes of crashes and security holes in C.
#include <stdlib.h> void free(void *ptr);
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.
Syntax
void free(void *ptr);
| Name | Description |
|---|---|
ptr |
Pointer previously returned by an allocation function, or NULL. |
Returns: nothing. It cannot report errors.
Errors / undefined behavior: passing a pointer that was not allocated by these functions (an array on the stack, a string literal, a pointer into the middle of a block), freeing the same block twice (double free), or accessing a block after freeing it are all undefined behavior. glibc often detects a double free and aborts with a message, but that is not guaranteed. See Memory errors.
Usage notes
free(NULL)does nothing. You need noif (p != NULL)guard, which keeps cleanup code short.- Pass the original pointer. If you advanced it (
p++), keep a copy of the start.free(p + 1)is undefined. - Nulling a freed pointer turns later accidental
freecalls into no-ops and later dereferences into immediate, debuggable crashes. It cannot fix copies of the pointer held elsewhere. - Free the contents first. For a struct that owns other allocations, free the members, then the struct (as in the
person_freepattern in malloc). - The memory is not necessarily returned to the OS. The allocator usually keeps it for reuse, so a process's memory use may not fall after
free. Large blocks may be unmapped. - Freed memory is not cleared. Secrets such as passwords stay in it; clear them with
memset_explicit(C23) orexplicit_bzero(glibc) before freeing. - Not for stack or static data. Only heap blocks are freed; arrays declared with
[]disappear on their own. - C23 adds
free_sized()andfree_aligned_sized()(in<stdlib.h>) that take the size too. They are optional hints and not in glibc 2.28, so code here uses plainfree. - Tools: Valgrind and the
-fsanitize=addressoption of GCC and Clang find leaks and misuse.