free
free(p) returns a malloc/calloc/realloc block to the allocator. After the call, p is a dangling pointer. free(NULL) is a defined no-op.
Detailed Explanation
Every successful malloc needs one free. Zero is a leak. Two is a double-free, which is undefined behavior. The allocator typically writes bookkeeping into the freed region; a later malloc may hand those bytes to someone else. Using the pointer after free is use-after-free.
free does not change your variable. It still holds the numeric address. Set p = NULL after free if that variable might be freed again or tested. That does not fix other copies of the pointer.
You may only free a pointer that came from the malloc family (or a NULL). free(&stack_obj), free(string_literal), and free of a pointer you offset into the block (free(p + 1)) are undefined. realloc moves; free the pointer it returned, not the old one.
free is not realloc(p, 0). It is not a destructor for pointees inside the block. If the block is a struct that owns other allocations, free those first, then the struct. That is widget_free.
Allocators are thread-safe. free in a signal handler is not safe. free after fork in a multithreaded program has constraints (only async-signal-safe functions in the child until exec).
Debug allocators (ASan, Valgrind, Guard Malloc) catch many bad frees. They do not catch a leak unless you also ask for leak detection. Turn both on.
Code Examples
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
char *p = malloc(8);
if (p == NULL) {
return 1;
}
p[0] = 'a';
p[1] = '\0';
printf("%s\n", p); /* prints: a */
free(p);
p = NULL;
free(p); /* no-op */
return 0;
}#include <stdlib.h>
#include <string.h>
struct Widget {
char *name;
};
static void widget_free(struct Widget *w)
{
if (w == NULL) {
return;
}
free(w->name);
free(w);
}
static struct Widget *widget_new(const char *name)
{
struct Widget *w = malloc(sizeof *w);
if (w == NULL) {
return NULL;
}
w->name = malloc(strlen(name) + 1);
if (w->name == NULL) {
free(w);
return NULL;
}
memcpy(w->name, name, strlen(name) + 1);
return w;
}Common Gotchas
`free(p + offset)` is undefined
free the pointer `malloc` returned.
Two `free`s of the same pointer is undefined behavior
`free(NULL)` is the only repeat that is safe.
`free` does not null out other copies
a stale copy is a use-after-free waiting to happen.
`free` does not run destructors on members
walk the object graph yourself.