Section 4.7

Double free

Definition

A double free is the error of releasing the same block of allocated memory twice. In C, a program obtains a block from the allocator, the library code that manages memory requested while the program runs, with the function malloc, and must hand the block back with the function free exactly once. The second free hands back a block that the allocator already holds as available. The records of the allocator can be damaged as a result, and the allocator may later give the same block to two different users.

The idea

A double free happens when two pieces of cleanup code each believe that freeing the block is their job. Take a function that builds an object and calls a second function to check it. The second function finds a fault, frees the object and reports failure. The first function sees the failure and runs its own error handling, which frees the object again.

A cloakroom gives a fair picture. The attendant keeps a list of free hooks and sends the next guest to the hook at the top of the list. A guest gives back hook 7, and the attendant writes 7 on the list. If the same return is recorded a second time, 7 is on the list twice, and the next two guests are both sent to hook 7. The picture stops being accurate in one respect. An attendant would notice that hook 7 is already on the list. A simple allocator does not look.

How it works

A simple allocator keeps the available blocks in a list, called a free list, and hands out the block that was freed most recently. The steps below use that scheme.

  1. p = malloc(16) takes block X from the free list.

  2. free(p) puts X back on the list.

  3. A second free(p) puts X on the list again. X is now on the list twice.

  4. a = malloc(16) receives X.

  5. b = malloc(16) receives X as well.

  6. The program stores one object through a and another through b. The two objects occupy the same bytes, and every write to one of them changes the other.

A second scenario does harm without damaging the list. Between the two calls to free, another part of the program allocates a block and receives X. The second free(p) then frees a block that this other part is using. From that moment every access by the other part is a use-after-free §4.6, a use of memory that has been freed.

Real allocators differ. Some detect certain double frees and stop the program. For steps 1 to 3, version 2.39 of glibc, the library that supplies malloc and free on many Linux systems, prints free(): double free detected in tcache 2 and aborts. Others damage their records without notice.

Double frees have two common causes: error handling, and confusion over which part of the program is responsible for freeing a block. A C function that acquires several resources often releases them at its end, at cleanup labels. A label is a named position in a function, and the statement goto jumps to it. Each error jumps to the label that releases what has been acquired so far, and execution then runs on through the labels below it, which release the earlier resources. A double free arises when one path releases a resource twice: once on the spot and once at a label, once in a called function and once in the caller, or once at each of two labels that both run.

Worked example

A function load allocates a candidate cand, a new object that is not yet in service, then a work buffer buf, and then parses input into the candidate. Its last lines are two cleanup labels:

err_free_buf: free(buf);
err_free_cand: free(cand); return -1;

A jump to err_free_buf frees the buffer, continues into err_free_cand, frees the candidate and returns the error value −1-1. A jump to err_free_cand frees only the candidate.

The author handles a failure of parsing like this:

if (parse(cand, buf) != 0) { free(cand); goto err_free_buf; }

Trace that path and count the calls to free for the candidate.

  1. free(cand) on the spot: the first free.

  2. The jump to err_free_buf: free(buf).

  3. Execution continues into err_free_cand: free(cand), the second free.

The candidate was allocated once and freed twice. Removing the free(cand) that was written on the spot leaves 1 allocation and 1 free on this path.

Stated precisely

The rule is stated for each allocation, not for each pointer variable and not for each address. For every block returned by an allocation function, the program may call free at most once, and it must call free exactly once to avoid a memory leak §4.8, memory that is never given back. The edition of the C standard published in 2011 puts it this way in its description of free: if the argument is a null pointer §4.26, no action occurs; otherwise, if the space has been deallocated by an earlier call to free or realloc, the behavior is undefined. A null pointer is a special pointer value that points to no object. Undefined behavior §4.12 means that the standard places no requirement on what the program does.

The count starts again with each allocation. If a block is freed, allocated again as a new object and freed by its new user, the address has been freed twice but each allocation has been freed once, which is correct. The error is two frees for one allocation. For the same reason an allocator cannot detect every double free: in the second scenario above, the second free names a block that is validly allocated at that moment.

Limits and common mistakes

Setting the pointer to null helps one variable. Because free of a null pointer does nothing, writing p = NULL, which makes p a null pointer, directly after free(p) makes a second free(p) harmless. A second pointer q that holds the same address is not changed, and free(q) is still a double free.

Detection by the allocator is not a guarantee. An allocator that aborts on some double frees misses others. AddressSanitizer §10.22, a tool that adds checks to a compiled program, reports double frees, but only on the paths that the tests run.

The function realloc also frees. A successful call to realloc, the function that changes the size of a block, deallocates the old block. Calling free on the old pointer afterwards is a double free.

Giving up a counted reference twice is the same mistake. With reference counting §9.22, an object carries a count of its users and is freed when the count reaches 0. A user that gives up its claim twice drives the count to 0 too early, and the object is freed while another user still holds it.

The lasting cure is a decision, not a check. For every function and every error path, decide which one part of the program frees each block. That rule is called ownership §4.2.

Questions answered

Do both cleanup labels release the same candidate on one error path?

They must not. If one error path runs two cleanup labels that both free the candidate, or frees the candidate on the spot and again at a label, that path contains a double free: the same block of memory is freed twice. A cleanup label is a named position near the end of a C function where resources are released. An error jumps to a label with the statement goto, and execution continues through the labels below it. A candidate is a newly built object that has not yet been put into service.

To answer the question for a real function, trace each error path separately. Start at the line where the error is detected, follow the jump, and list every free that runs before the return, including every free inside a function that was called on the way. Each allocated block must appear in the list exactly once. A block that appears twice is a double free, which can make the allocator hand the same memory to two users. A block that appears zero times, and that no other part of the program has taken over, is a memory leak: its memory is never given back.

Related entries: Ownership (§4.2), Object lifetime (§4.1), Reference counting (§9.22), Use-after-free (§4.6), Memory leak (§4.8). Further reading: [25, 78].