# Memory Debugging: ASan & Valgrind — C Programming Fundamentals: Pointers, Memory and Files

Source: https://www.geekswithgeeks.com/en/c/c-memory-debugging

> Catch buffer overflows, leaks and use-after-free bugs with AddressSanitizer and Valgrind instead of guessing.

## AddressSanitizer

Compile with `-fsanitize=address` and the program reports out-of-bounds access, use-after-free and leaks with a stack trace.

```bash
gcc -g -O1 -fsanitize=address,undefined -fno-omit-frame-pointer prog.c -o prog
./prog
# ERROR: AddressSanitizer: heap-buffer-overflow ... at prog.c:12
```

## Valgrind

Valgrind runs the unmodified binary and reports invalid reads and leaked blocks, but it is slower.

```bash
gcc -g prog.c -o prog
valgrind --leak-check=full ./prog
```

Run tests under a sanitizer in CI. Sanitizer builds are for development, not production, because they slow programs and use more memory.
