Skip to content
systemcoding.dev
Security

Report leaks at exit with ASAN_OPTIONS=detect_leaks=1

Set ASAN_OPTIONS=detect_leaks=1 to make AddressSanitizer report leaked allocations at exit, on platforms where leak checking is not on by default.

1 min read
Summarize in AI

AddressSanitizer bundles LeakSanitizer, and on Linux x86-64 it runs at exit without any setting. On other platforms, including macOS, it is off until you ask for it, and an explicit detect_leaks=1 documents the intent everywhere. The report arrives after main returns, with the allocation stack of every block that was still reachable only through a lost pointer.

leak.cc
#include <stdlib.h>

static void *keep;

int main(void)
{
    keep = malloc(16);
    keep = NULL;
    return 0;
}
Shell
clang -g -O0 -fsanitize=address leak.c -o leak
ASAN_OPTIONS=detect_leaks=1 ./leak 2>&1 | grep SUMMARY
Text
SUMMARY: AddressSanitizer: 16 byte(s) leaked in 1 allocation(s).

Set detect_leaks=0 to turn the check off for a program you know leaks on purpose, such as a short-lived tool. LeakSanitizer uses ptrace to stop the process and scan memory, so it can fail inside a container that forbids it or under a debugger, with a message about being unable to attach. Compile without optimisation while hunting, because the optimiser can delete a leak you meant to see. The options are listed in the AddressSanitizer flags page.

Also inDebugging
Share

More snippets

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.