14. Debugging and sanitizers: gdb/lldb, Valgrind, ASan/UBSan
14.1 AddressSanitizer — catch memory bugs the instant they happen
clang -std=c17 -g -fsanitize=address -o buggy buggy.c
./buggy
// buggy.c
#include <stdlib.h>
int main(void) {
int *arr = malloc(5 * sizeof(int));
arr[5] = 1; // one past the end
free(arr);
return 0;
}
Running this under ASan prints a precise report: heap-buffer-overflow,
the exact line of the bad write, and the exact line of the malloc that
created the buffer — versus a plain build, which might not crash at all
(the overflow lands in unused allocator padding) and ship the bug to
production. Every project in this guide should be tested under
-fsanitize=address,undefined before you trust it.
14.2 UndefinedBehaviorSanitizer — catch UB, not just memory bugs
clang -std=c17 -g -fsanitize=undefined -o ubtest ubtest.c
#include <limits.h>
int main(void) {
int x = INT_MAX;
return x + 1; // UBSan: "signed integer overflow: 2147483647 + 1 cannot be
// represented in type 'int'"
}
14.3 Valgrind — the other lens (great for leak detection on Linux)
valgrind --leak-check=full --show-leak-kinds=all ./buggy
Valgrind runs your binary on a software CPU and tracks every allocation;
it's slower than ASan but doesn't require recompiling, and its leak
reports (definitely lost, still reachable) are the standard vocabulary
for memory-leak triage in C/C++ shops.
14.4 A five-minute gdb/lldb session
clang -g -O0 -o buggy buggy.c
lldb ./buggy # or: gdb ./buggy
(lldb) run
(lldb) bt # backtrace — where did it crash?
(lldb) frame select 1 # move up the stack
(lldb) print arr[3] # inspect a value
(lldb) break main.c:12 # set a breakpoint
(lldb) continue
Real-world example. The standard triage loop in production C: a core
dump or crash report comes in → load it in gdb/lldb (gdb ./app core) →
bt for the backtrace → walk frames with frame select N → inspect
variables. This is the exact workflow used to debug the segfaults you'll
intentionally cause in Section 10.2's exercises, and the real ones you'll
cause by accident for the rest of your C career.