Double Free
A double-free is calling free twice on the same allocation. The second call is undefined behavior. Allocators often crash, or they corrupt the heap so a later malloc blows up far from the bug.
Detailed Explanation
free hands the block back to a freelist. A second free treats the same address as a live block again and inserts it twice, or it reads metadata the first free already smashed. The next malloc may return the same pointer to two callers. Each writes. That is a security bug as well as a crash.
The usual sources: two error paths that both clean up; a widget_free that frees a member the caller also frees; a copy of a struct that owns a pointer (shallow copy, two owners); realloc that already freed the old block on a move, plus a free of the old pointer.
free(NULL) is not a double-free. It is defined. The idiom free(p); p = NULL; makes a second free(p) on that variable safe. It does not fix q if q == p.
Ownership in the type is the design fix. One function frees. The header says so. After a successful transfer (widget_free consumes the pointer), the caller does not free. After a failed init, either init cleaned up or it did not; it must not be both.
Detect with ASan (-fsanitize=address) or Valgrind. They print two stack traces: the first free and the second. That pair is enough to find the extra owner.
Code Examples
#include <stdlib.h>
#include <string.h>
struct Widget {
char *name;
};
static void widget_free(struct Widget *w)
{
if (w == NULL) {
return;
}
free(w->name);
w->name = NULL;
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;
}
int main(void)
{
struct Widget *w = widget_new("n");
widget_free(w);
/* widget_free(w) again would be a double-free of w */
return 0;
}Common Gotchas
`p = NULL` after free only protects that variable
aliases still point at the dead block.
Shallow-copying an owning struct and freeing both copies is a double-free of the
Shallow-copying an owning struct and freeing both copies is a double-free of the member
Freeing the old pointer after a successful `realloc` that moved the block is a d
Freeing the old pointer after a successful `realloc` that moved the block is a double-free
`free(NULL)` is safe and is the reason cleanup functions start with a NULL check
`free(NULL)` is safe and is the reason cleanup functions start with a NULL check