TExcelTAD
Home › Memory Safety & Binary Exploitation Concepts › Double Free and Invalid Free (CWE-415)

Double Free and Invalid Free (CWE-415)

free(p) hands a block back to the allocator, which records it in a free list. Calling free(p) a second time records the same block twice. From then on the allocator believes it has two free blocks where there is one, and two later malloc calls of that size can return the same address to two different owners: a use-after-free created by the allocator itself. A related bug is the invalid free: passing free a pointer that malloc never returned (a pointer into the middle of a block, a stack address, a string literal), which makes the allocator interpret arbitrary bytes as a chunk header. Both corrupt the allocator's own state, which is why glibc now checks for them and aborts.

The bug in a toy program

Double frees almost always come from error paths. In the toy, parse duplicates a message and, if the message is too long, frees the copy and reports failure. The caller follows a common convention, "always clean up the struct, whatever happened", and frees the body again. Short messages work; a long one triggers the bug:

bash · try it yourself
cat > df.c <<'SRC'
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

struct msg { char *body; };

static int parse(struct msg *m, const char *text) {
    m->body = strdup(text);
    if (strlen(text) > 8) {          /* too long: clean up and fail */
        free(m->body);               /* BUG: m->body still points at the freed block */
        return -1;
    }
    return 0;
}

static void msg_cleanup(struct msg *m) { free(m->body); }

int main(int argc, char **argv) {
    struct msg m;
    if (parse(&m, argc > 1 ? argv[1] : "hello") != 0)
        fprintf(stderr, "parse failed\n");
    msg_cleanup(&m);                 /* the caller always cleans up */
    return 0;
}
SRC
gcc -g -O0 df.c -o df
./df hello && echo "short input: ok"
./df a-long-message 2>&1 | cat; echo "exit code: ${PIPESTATUS[0]}"
echo "== with ASan"
gcc -g -O0 -fsanitize=address df.c -o df-asan
./df-asan a-long-message 2>&1 | grep -E 'ERROR|located|freed by|previously|df.c'
short input: ok
parse failed
free(): double free detected in tcache 2
exit code: 134
== with ASan
==23==ERROR: AddressSanitizer: attempting double-free on 0x502000000010 in thread T0:
    #1 0x5d6662ce0362 in msg_cleanup /home/learner/df.c:16
    #2 0x5d6662ce04a4 in main /home/learner/df.c:22
0x502000000010 is located 0 bytes inside of 15-byte region [0x502000000010,0x50200000001f)
freed by thread T0 here:
    #1 0x5d6662ce0314 in parse /home/learner/df.c:10
    #2 0x5d6662ce044d in main /home/learner/df.c:20
previously allocated by thread T0 here:
    #1 0x5d6662ce02c8 in parse /home/learner/df.c:8
    #2 0x5d6662ce044d in main /home/learner/df.c:20

Without ASan, glibc's tcache noticed that the block being freed was already in its free list (since glibc 2.29 each chunk in the tcache carries a key; a free that finds the key searches the bin) and aborted with free(): double free detected in tcache 2. The check is cheap and catches the common case. It is not complete: when the tcache bin for a size is full (7 entries by default), freed chunks go to other lists with weaker checks (the fastbin check only compares the chunk with the head of its list), and older allocators had no check at all.

The report, line by line

  • attempting double-free on … in thread T0: the kind.
  • The first stack is the second free: msg_cleanup df.c:16, called from main df.c:22.
  • 0 bytes inside of 15-byte region: the block is the strdup of "a-long-message" (14 characters + NUL).
  • freed by … parse df.c:10: the first free, in the error path.
  • previously allocated by … parse df.c:8: the strdup.

So the report shows both frees, which is exactly what you need: the bug is not in either free alone but in the disagreement about who owns m->body after a failure.

Invalid free

free must receive exactly a pointer that malloc, calloc, realloc or strdup returned, or NULL. The second toy frees a pointer to the value inside a key=value string. GCC 13 already warns at compile time (-Wfree-nonheap-object, on by default), glibc aborts at run time, and ASan names the offset:

bash · try it yourself
cat > inv.c <<'SRC'
#include <stdlib.h>
#include <string.h>
int main(void) {
    char *buf = malloc(32);
    strcpy(buf, "key=value");
    char *val = strchr(buf, '=') + 1;
    free(val);                       /* BUG: not the pointer malloc returned */
    return 0;
}
SRC
gcc -g -O0 inv.c -o inv 2>&1 | grep warning
./inv 2>&1 | cat; echo "exit code: ${PIPESTATUS[0]}"
gcc -g -O0 -fsanitize=address inv.c -o inv-asan 2>/dev/null
./inv-asan 2>&1 | grep -E 'ERROR|located|inv.c'
inv.c:7:5: warning: ‘free’ called on pointer ‘buf’ with nonzero offset [1, 32] [-Wfree-nonheap-object]
free(): invalid pointer
exit code: 134
==23==ERROR: AddressSanitizer: attempting free on address which was not malloc()-ed: 0x503000000044 in thread T0
    #1 0x5a037b46f282 in main /home/learner/inv.c:7
0x503000000044 is located 4 bytes inside of 32-byte region [0x503000000040,0x503000000060)
allocated by thread T0 here:
    #1 0x5a037b46f23e in main /home/learner/inv.c:4

attempting free on address which was not malloc()-ed, located 4 bytes inside of 32-byte region: val is buf + 4. glibc's own check (free(): invalid pointer) rejected it because buf + 4 isn't aligned like a pointer malloc returns; an aligned wrong pointer would have made glibc read whatever bytes lie before it as a chunk header.

Root cause

Unclear ownership on failure. parse treated m->body as its own to free on error; main treated it as its own to free always. Either convention is fine; mixing them is the bug.

The fix

Pick one convention and make the code enforce it. Here: a function that fails leaves the struct in a state that is safe to clean up (pointers NULL), and cleanup is idempotent, because free(NULL) does nothing:

c · try it yourself
#define _POSIX_C_SOURCE 200809L   /* for strdup in strict C17 mode */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

struct msg { char *body; };

static int parse(struct msg *m, const char *text) {
    m->body = NULL;
    char *copy = strdup(text);
    if (!copy) return -1;
    if (strlen(text) > 8) { free(copy); return -1; }   /* nothing escapes on failure */
    m->body = copy;                                    /* ownership moves only on success */
    return 0;
}

static void msg_cleanup(struct msg *m) { free(m->body); m->body = NULL; }

int main(void) {
    const char *inputs[] = {"hello", "a-long-message"};
    for (int i = 0; i < 2; i++) {
        struct msg m;
        int rc = parse(&m, inputs[i]);
        printf("%-15s rc=%2d body=%s\n", inputs[i], rc, m.body ? m.body : "(null)");
        msg_cleanup(&m);
        msg_cleanup(&m);                               /* a second cleanup is now harmless */
    }
    return 0;
}
hello           rc= 0 body=hello
a-long-message  rc=-1 body=(null)

The failed parse leaves body NULL, so the caller's cleanup (here run twice on purpose) frees nothing. The long input is the regression test: under ASan the old code fails it with attempting double-free, the new code passes.

How double and invalid frees are detected

  • ASan reports both, with all relevant stacks.
  • glibc's checks abort on the simple cases (double free detected in tcache 2, double free or corruption (fasttop), free(): invalid pointer); in production logs these are security bugs.
  • Compiler warnings: -Wfree-nonheap-object (default on) and -Wanalyzer-double-free with GCC's -fanalyzer; Clang's static analyzer unix.Malloc checker.
  • Review: every free on an error path; every struct with an owned pointer and a cleanup function; every goto fail sequence.

The CWE

CWE-415: Double Free. Invalid frees are CWE-590 (Free of Memory not on the Heap) or CWE-761 (Free of Pointer not at Start of Buffer). Both lead to the memory-corruption effects of CWE-416.

Pitfalls

  • Two cleanups of the same struct after copying it by value (struct msg copy = m;): both copies own the same pointer. Copying an owning struct needs a deep copy or a transfer.
  • realloc failure: p = realloc(p, n) loses the old block on failure (a leak); freeing both the old and new pointer after a moving realloc is a double free.
  • Signal handlers or threads freeing shared objects without synchronisation produce double frees that only show under load.

Practice

1. Why does making msg_cleanup set m->body = NULL help?

free(NULL) is defined to do nothing, so a second cleanup of the same struct becomes harmless. It doesn't help if another struct holds a copy of the pointer.

2. Which line of the ASan report shows the error-path free?

freed by thread T0 here: … in parse /home/learner/df.c:10.

3. free(a); free(b); free(a); with blocks of the same small size: does glibc 2.39 catch it?

Yes, while the blocks go to the tcache: since 2.29 each chunk in the tcache carries a key that marks it as free, and free checks the key and then searches the bin. If the bin is full and the chunks go to a fastbin, the "fasttop" check compares only with the head of the list (b) and misses the second free(a). ASan catches it in every case.

Test yourself

What is the immediate danger of a double free?

  1. A memory leak
  2. The allocator lists the block twice, so two later mallocs can return the same address to two owners
  3. The program gets slower
  4. Nothing

Where did the toy's first free happen?

  1. msg_cleanup
  2. In parse's error path, df.c:10
  3. In main
  4. In strdup

Which fix removes the bug class rather than one instance?

  1. Remove the free in msg_cleanup
  2. A convention enforced by code: on failure nothing escapes, ownership moves only on success, cleanup is idempotent
  3. Catch SIGABRT
  4. Use calloc

What did ASan say about free(val) where val = buf + 4?

  1. double-free
  2. attempting free on address which was not malloc()-ed, located 4 bytes inside of 32-byte region
  3. heap-buffer-overflow
  4. memory leak