TExcelTAD
Home › Memory Safety & Binary Exploitation Concepts › Memory Leaks and LeakSanitizer (CWE-401)

Memory Leaks and LeakSanitizer (CWE-401)

A memory leak is memory that is allocated and never freed after the program has lost every pointer to it. A leak corrupts nothing, so it isn't a memory-corruption bug, but it is still a security problem: a server that leaks a few hundred bytes per malformed request can be made to grow until the operating system kills it, which is a denial of service an attacker controls. Leaks are also the most common symptom of broken ownership rules, the same confusion that, handled the other way, becomes a double free. Short-lived command-line tools can get away with leaking; daemons, libraries and anything parsing untrusted input can't.

Definitions

  • Direct leak: a block that no pointer anywhere in the program refers to any more.
  • Indirect leak: a block that is still pointed to, but only from blocks that are themselves leaked (a struct's fields when the struct leaked).
  • Still reachable: memory with a live pointer to it at exit (a global cache). Not a leak in LeakSanitizer's sense, and not reported by default.
  • LeakSanitizer (LSan): at exit, scans the stacks, registers and globals for pointers into the heap (like a conservative garbage collector) and reports every block it can't reach. On Linux it is on automatically with ASan, or alone with -fsanitize=leak.

The bug in a toy program

load_user allocates a user record and two strings, then validates the email. On a bad email it returns NULL without freeing what it already allocated. The caller reports "invalid email" and continues, exactly as it should. Every invalid record leaks three blocks:

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

struct user { char *name; char *email; };

static struct user *load_user(const char *name, const char *email) {
    struct user *u = malloc(sizeof *u);
    u->name = strdup(name);
    u->email = strdup(email);
    if (!strchr(email, '@'))
        return NULL;                  /* BUG: u, u->name and u->email are lost */
    return u;
}

int main(void) {
    setvbuf(stdout, NULL, _IONBF, 0);
    const char *emails[] = {"alice@lab.test", "bob-at-lab.test", "carol@lab.test"};
    const char *names[] = {"alice", "bob", "carol"};
    for (int i = 0; i < 3; i++) {
        struct user *u = load_user(names[i], emails[i]);
        if (!u) { printf("%s: invalid email\n", names[i]); continue; }
        printf("%s: ok\n", u->name);
        free(u->name); free(u->email); free(u);
    }
    return 0;
}
SRC
gcc -g -O0 -fsanitize=address leak.c -o leak && ./leak 2>&1 | grep -vE '#[2-9] |^$|====='
echo "exit code: ${PIPESTATUS[0]}"
echo "== LeakSanitizer alone (much cheaper than ASan)"
gcc -g -O0 -fsanitize=leak leak.c -o leak-lsan && ./leak-lsan 2>&1 | grep -E 'SUMMARY'
alice: ok
bob: invalid email
carol: ok
==15==ERROR: LeakSanitizer: detected memory leaks
Direct leak of 16 byte(s) in 1 object(s) allocated from:
    #0 0x7c8e756589c7 in malloc ../../../../src/libsanitizer/asan/asan_malloc_linux.cpp:69
    #1 0x5fe602fb3306 in load_user /home/learner/leak.c:8
Indirect leak of 16 byte(s) in 1 object(s) allocated from:
    #0 0x7c8e756524e8 in strdup ../../../../src/libsanitizer/asan/asan_interceptors.cpp:578
    #1 0x5fe602fb334d in load_user /home/learner/leak.c:10
Indirect leak of 4 byte(s) in 1 object(s) allocated from:
    #0 0x7c8e756524e8 in strdup ../../../../src/libsanitizer/asan/asan_interceptors.cpp:578
    #1 0x5fe602fb3316 in load_user /home/learner/leak.c:9
SUMMARY: AddressSanitizer: 36 byte(s) leaked in 3 allocation(s).
exit code: 1
== LeakSanitizer alone (much cheaper than ASan)
SUMMARY: LeakSanitizer: 36 byte(s) leaked in 3 allocation(s).

The report, line by line

  • LeakSanitizer: detected memory leaks: printed at exit, after the program's normal output.
  • Direct leak of 16 byte(s) in 1 object(s) allocated from … load_user leak.c:8: the struct user (two 8-byte pointers). Nothing points to it after return NULL.
  • Indirect leak of 16 byte(s) … leak.c:10 and Indirect leak of 4 byte(s) … leak.c:9: the two strings, "bob-at-lab.test" (15 + NUL) and "bob" (3 + NUL). They are "indirect" because the leaked struct still points to them. Fix the direct leak and the indirect ones usually disappear with it.
  • SUMMARY: … 36 byte(s) leaked in 3 allocation(s), and exit code 1: LSan makes the process fail, so a leak breaks a test run.

Each record of the report groups identical allocation stacks: a loop that leaked a thousand times shows in 1000 object(s), which immediately tells you the leak scales with input.

Root cause

An early return on an error path, between acquiring resources and handing them to the caller. It is the C version of "forgot to close the file": every exit of a function must release what that function acquired and hasn't transferred.

The fix

The standard C idiom is a single cleanup label that frees in reverse order of allocation. free(NULL) is a no-op, so partially built objects need no special cases:

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 user { char *name; char *email; };

static void user_free(struct user *u) {
    if (!u) return;
    free(u->name);
    free(u->email);
    free(u);
}

static struct user *load_user(const char *name, const char *email) {
    struct user *u = calloc(1, sizeof *u);    /* fields start NULL */
    if (!u) return NULL;
    u->name = strdup(name);
    u->email = strdup(email);
    if (!u->name || !u->email || !strchr(email, '@'))
        goto fail;
    return u;                                 /* ownership moves to the caller */
fail:
    user_free(u);                             /* everything acquired so far */
    return NULL;
}

int main(void) {
    const char *emails[] = {"alice@lab.test", "bob-at-lab.test", "carol@lab.test"};
    const char *names[] = {"alice", "bob", "carol"};
    int ok = 0;
    for (int i = 0; i < 3; i++) {
        struct user *u = load_user(names[i], emails[i]);
        if (u) ok++;
        printf("%s: %s\n", names[i], u ? "ok" : "invalid email");
        user_free(u);
    }
    printf("%d of 3 loaded\n", ok);
    return 0;
}
alice: ok
bob: invalid email
carol: ok
2 of 3 loaded

Validating before allocating (check the email first) would be simpler still; the goto fail shape is what you need when validation depends on what was allocated. In C++ the same rule is automatic with RAII: a std::unique_ptr<User> and std::string members free themselves on every return path (Modern C++).

How leaks are detected

  • LSan in every ASan test run, and -fsanitize=leak alone where ASan is too slow.
  • Valgrind Memcheck (valgrind --leak-check=full ./prog) reports "definitely lost" (direct), "indirectly lost" and "still reachable" without recompiling, typically 10–50x slower (the Valgrind manual's range).
  • In production: resident memory that grows with request count (monitor RSS per process), heap profilers (heaptrack, jemalloc and tcmalloc profiling), and a load test that sends the same malformed request in a loop and checks that memory stays flat.
  • Static analysis: GCC's -fanalyzer (-Wanalyzer-malloc-leak) and Clang's static analyzer find leaks on error paths within a function.

The CWE

CWE-401: Missing Release of Memory after Effective Lifetime. When the attacker can trigger it repeatedly, it is also CWE-400 (Uncontrolled Resource Consumption) and CWE-789 (Memory Allocation with Excessive Size Value) is its cousin: a single request that makes the program allocate a huge, attacker-chosen size.

Pitfalls

  • Suppressing instead of fixing. LSan suppressions (LSAN_OPTIONS=suppressions=file) are for third-party libraries you can't change, not for your own code.
  • "The OS frees everything at exit." True for a tool that runs once. A library has no idea how long its host process lives.
  • realloc on failure: p = realloc(p, n); overwrites the only pointer to the old block with NULL when realloc fails. Use a temporary.
  • Leaking file descriptors, locks and threads has the same shape and the same fix, but LSan doesn't see them.

Practice

1. Why is the struct reported as a direct leak and the strings as indirect?

After return NULL, no live pointer refers to the struct. The strings are still referenced, from the struct's fields, but the struct itself is unreachable, so they are reachable only through leaked memory.

2. How would the report change if the input had 1,000 invalid users?

The same three records, with in 1000 object(s) and 1000 times the byte counts (16 000, plus the string sizes, which vary with each name and email).

3. Is a global cache that is never freed a leak?

Not for LSan: it is still reachable through a global pointer at exit. It can still be a resource problem if it grows without bound; give caches a maximum size and an eviction policy.

Test yourself

What makes a memory leak a security issue?

  1. It corrupts the heap
  2. An attacker who can trigger it repeatedly can exhaust memory and crash or degrade the service (denial of service)
  3. It leaks secrets
  4. It disables ASLR

In the report, which allocation is the direct leak?

  1. The strdup of the email
  2. The malloc of struct user at leak.c:8
  3. The strdup of the name
  4. printf's buffer

How many bytes leaked in total in the toy?

  1. 16
  2. 20
  3. 36
  4. 52

Which C idiom fixes leaks on error paths?

  1. return NULL early
  2. A single cleanup label (goto fail) that frees what was acquired, relying on free(NULL) being a no-op
  3. Using global variables
  4. Calling exit()