free(3)
C library function
Returns a block from malloc, calloc or realloc to the heap. free(NULL) is safe; freeing twice, or a pointer that was never allocated, is undefined behavior.
from malloc);
Frees memorythe block is given back: p must not be used again
Other common calls
- free(NULL);
- does nothing, and is allowed
#include <stdlib.h>
void free(void *ptr);Description
free hands a heap block back so that it can be reused. Its argument must be an address returned by malloc(3), calloc(3) or realloc(3), exactly as it was returned. Not a pointer into the middle of the block, not a stack variable, not a string literal.
Only one case is completely safe: free(NULL) does nothing. The standard guarantees it, and it spares you a pile of if (p != NULL) checks before every release. Everything else is yours to watch. Freeing the same block twice, or passing a pointer that did not come from the heap, is undefined behavior. With glibc (a typical Linux system), it shows up as a message such as free(): double free detected in tcache 2 or free(): invalid pointer followed by Aborted; with musl (Alpine, the environment of Grademe exercises), as a plain segmentation fault. Both cases are covered in double free detected.
Return value
None: free returns void. After the call, the pointer you passed no longer refers to anything valid, and reading it or freeing it again is undefined behavior. The useful habit is free(p); p = NULL;, since a later free(NULL) will do nothing.
Example
#include <stdio.h>#include <stdlib.h>
int main(void){ char *name = NULL;
free(name); /* no effect, and that is guaranteed */ name = malloc(8); if (name == NULL) return 1; free(name); name = NULL; /* no dangling pointer left */ return 0;}Pitfalls
Double
free: freeing the same block twice. Set the pointer toNULLafter the first call.Freeing a shifted pointer (
free(p + 1), or apyou incremented in a loop): keep the original pointer to hand back.freeon a stack variable or a string literal: those addresses do not come from the heap.Using the block after
free(use after free): the memory gets recycled, and its contents no longer belong to you.
free_str_array
Write free_str_array, which frees every string of a NULL-terminated array before the array itself and returns how many strings it freed.
Cited in
- C23 new features: nullptr, constexpr, #embed by example
- free(): double free detected in tcache 2 in C
- Learn C programming in 2026: where to start
- Valgrind output explained: Invalid read, definitely lost
- implicit declaration of function in C: causes and fix
- Linked list in C: insert, delete and free without leaks
- malloc, calloc, realloc and free in C: the differences
- Pointers in C explained with memory diagrams
- Stack vs heap in C: difference, lifetime and size
- Strings in C: '\0', strlen, strcpy vs strncpy, strcmp
- Undefined behavior in C: works on my machine, not on yours
- Valgrind on Mac M1 and Windows: what to use in 2026