Use AddressSanitizer to find memory leaks in C programs

To use AddressSanitizer, compile your program with the -fsanitize=adress flag.

As an example, let’s take the following program1, which leaks 100 bytes before printing “Hello World”:

#include <stdio.h>
#include <stdlib.h>

void *p;
int main() {
  p = malloc(100);
  p = 0; // The memory is leaked here.

  printf("hello, world\n");

Leak detection doesn’t work with Apple’s bundled clang version. Although running AddressSanitizer should work on LLVM, I opted for running it in a Linux-based containter:

FROM buildpack-deps:bullseye
COPY hello.c hello.c
RUN gcc -fsanitize=address hello.c
CMD ASAN_OPTIONS=detect_leaks=1 ./a.out
gcc -fsanitize=address hello.c
Compiles the hello.c program with the -fsanitize=address flag, which enables AddressSanitizer.
CMD ASAN_OPTIONS=detect_leaks=1 ./a.out
Runs the produced program (a.out) with leak detection enabled.

Then, build the container and run the example, which locates the 100 bytes of memory leaked in the program:

docker build -t asan-example .
docker run --rm -- asan-example
==7==ERROR: LeakSanitizer: detected memory leaks

Direct leak of 100 byte(s) in 1 object(s) allocated from:
    #0 0x7f5d82f77e8f in __interceptor_malloc ../../../../src/libsanitizer/asan/asan_malloc_linux.cpp:145
    #1 0x55562a9b4192 in main //hello.c:6
    #2 0x7f5d82d1dd09 in __libc_start_main (/lib/x86_64-linux-gnu/

SUMMARY: AddressSanitizer: 100 byte(s) leaked in 1 allocation(s).

  1. Taken from LLVM’s LeakSanitizer documentation ↩︎