Lesson 38 / 38
Memory Debugging: ASan & Valgrind
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.
gcc -g -O1 -fsanitize=address,undefined -fno-omit-frame-pointer prog.c -o prog
./prog
# ERROR: AddressSanitizer: heap-buffer-overflow ... at prog.c:12Valgrind
Valgrind runs the unmodified binary and reports invalid reads and leaked blocks, but it is slower.
gcc -g prog.c -o prog
valgrind --leak-check=full ./progRun tests under a sanitizer in CI. Sanitizer builds are for development, not production, because they slow programs and use more memory.