Debugging with gdb, valgrind & sanitizers
Find crashes, leaks and memory errors with gdb, valgrind and AddressSanitizer.
By Invicly Tech, , in Linux System Programming. About 10 minutes to read.
In short
C has no runtime checks, so memory errors often corrupt data silently or crash far from the real bug. gdb lets you stop a program and inspect its state, valgrind memcheck detects leaks and invalid accesses, and AddressSanitizer compiles checks directly into your binary. Using them routinely turns hours of guessing into minutes.
Explained simply
C does not warn you at run time when you make a memory mistake. A program might read past an array, keep running, and crash much later somewhere unrelated. That is why guessing rarely works and tools matter so much.
gdb is a debugger. It lets you pause a program, look at variables, step one line at a time and see the chain of function calls. When a program crashes, gdb shows exactly which line it was on.
valgrind and AddressSanitizer are memory checkers. They watch every memory access and shout the moment something is wrong: reading freed memory, writing past a buffer, or forgetting to free. They point at the real bug, not the place it finally crashed.
A good habit is simple: build with -g, run your tests under AddressSanitizer, and open gdb whenever something crashes. You will spend far less time staring at code.
Press Play on a diagram to walk through it one step at a time.
- Breakpoints, stepping, watchpoints
- Backtraces from crashes and core dumps
- Inspect variables and memory
- Needs only a -g build
- Leaks, invalid reads and writes
- Use of uninitialised values
- Runs the unmodified binary
- Roughly 10 to 50 times slower
- Build with -fsanitize=address -g
- Overflows, use-after-free, leaks
- About 2 times slower
- Ideal for tests and CI
- 1Reproduce
Find input that triggers it every time
- 2Rebuild
-g -O0 -fsanitize=address
- 3Read report
First error, its stack and allocation site
- 4Inspect
gdb: break near the site, print values
- 5Fix and add test
Keep the input as a regression test
In depth
A gdb session that actually finds the bug
Start with gdb ./app, then run with any arguments. When it crashes, type bt to print the backtrace: the list of function calls from main down to the crash. frame 2 jumps to a caller, list shows nearby source, and print var or print *ptr shows values.
If you know roughly where the trouble starts, use break file.c:42 and run again. Then next steps over a line, step goes into a function call, and finish runs until the current function returns. A watchpoint, watch total, stops whenever a variable changes, which is perfect for "who is overwriting this?" bugs.
- bt: who called whom
- break, run, next, step, finish
- print and display to inspect
- watch var stops on every change
- info locals shows all locals
- 1gdb ./app, then run
Program runs until it crashes
- 2bt
Calls from main down to the crash
- 3frame 2, list
Jump to a caller, see its source
- 4print var
Check the values
- 5break file.c:42, run
Stop earlier, then next and step
Core dumps: debugging after the fact
Sometimes a crash happens on a server or only once in a while. A core dump is a snapshot of the process memory at the moment it died. Enable them in your shell with ulimit -c unlimited. On many modern distros systemd-coredump captures them; list them with coredumpctl list and open the latest with coredumpctl gdb.
With a plain core file, run gdb ./app core and type bt. You get the same backtrace as if you had been running under gdb live. This is why release builds often keep debug symbols in a separate file: you can still read core dumps from production without shipping a large binary.
- 1ulimit -c unlimited
Allow core dumps
- 2Program crashes
Memory snapshot saved
- 3coredumpctl list
On systemd-coredump systems
- 4coredumpctl gdb
Or gdb ./app core
- 5bt
Same backtrace as a live session
Reading a valgrind or ASan report
Both tools print a report with three useful parts. First, the kind of error, such as "Invalid write of size 4" or "heap-buffer-overflow". Second, the stack trace where the bad access happened. Third, the history of the memory: where it was allocated and, for use-after-free, where it was freed.
Read the first error first. Later errors are often side effects of the first one. For leaks, valgrind sorts them into "definitely lost" (a real leak), "indirectly lost" (lost because its parent was lost), and "still reachable" (memory still pointed to at exit, usually harmless).
- Fix the first error before the rest
- Definitely lost = real leak
- ASAN_OPTIONS=detect_leaks=1 is on by default on Linux
Choosing a tool in practice
Use AddressSanitizer for daily development and tests. It needs a rebuild with -fsanitize=address -g, but it is fast enough to leave on in your test suite and catches overflows on the stack and globals too, which valgrind misses. Add -fsanitize=undefined to catch things like signed integer overflow.
Use valgrind when you cannot rebuild, for example with a binary someone else compiled, or when you want to detect reads of uninitialised memory, which ASan does not report (MemorySanitizer does, but only with clang). Use gdb when you need to understand the flow of the program, not just find a bad access.
Learn it in 4 short steps
About 1h each. Track them with a timer in your plan.
- 1Set breakpoints and step in gdb~1h
- 2Inspect a core dump backtrace~1h
- 3Find leaks with valgrind memcheck~1h
- 4Catch overflows with -fsanitize=address~1h
Key points
- Build debug binaries with -g -O0 so gdb maps machine code to source lines.
- bt in gdb shows the call stack at the moment of a crash.
- Enable core dumps with ulimit -c unlimited to debug crashes after the fact.
- Run valgrind --leak-check=full and fix definitely lost blocks first.
Key terms
Tap a card to flip it. 0/6 known
Examples
gcc -g -O0 -o app app.c
gdb --args ./app input.txt
(gdb) break parse_line
(gdb) run
(gdb) bt
(gdb) print *req
valgrind --leak-check=full ./app input.txt
gcc -g -fsanitize=address,undefined -o app app.c && ./app input.txtStep through with gdb, then hunt leaks with valgrind and overflows with ASan.
Catching an off-by-one with AddressSanitizer
The loop below uses <= instead of <, so it writes one int past the end of a 5-int heap block. Without ASan it often runs silently. With ASan the program stops at the bad write and reports heap-buffer-overflow, the line number, and that the block was allocated by malloc in main. Change <= to < and the report disappears.
/* gcc -g -fsanitize=address -o oob oob.c && ./oob */
#include <stdio.h>
#include <stdlib.h>
int main(void) {
int *a = malloc(5 * sizeof *a);
if (!a) { perror("malloc"); return 1; }
for (int i = 0; i <= 5; i++) /* bug: should be i < 5 */
a[i] = i;
printf("%d\n", a[0]);
free(a);
return 0;
}Finding who corrupts a variable with a watchpoint
A counter called total ends up with a crazy value. Rather than reading every function, we let gdb watch it. Each time total changes, gdb stops and prints the old value, the new value and the line responsible. After a few continues we land on the line that writes through a wrong pointer.
gcc -g -O0 -o app app.c
gdb ./app
(gdb) break main
(gdb) run
(gdb) watch total
(gdb) continue # Old value = 0, New value = 10, at app.c:31
(gdb) continue # Old value = 10, New value = 1952805748, at app.c:58
(gdb) bt # shows which caller reached line 58
(gdb) print buf # look at the buffer next to totalQuick reference
- gcc -g -O0 for the clearest debugging
- gdb --args ./app a b passes arguments to the program
- bt, frame N, print x, info locals in gdb
- watch x stops whenever x changes
- ulimit -c unlimited enables core files; coredumpctl gdb opens the latest
- valgrind --leak-check=full --track-origins=yes ./app
- gcc -g -fsanitize=address,undefined for tests and CI
- Fix the first reported error first
Common mistakes
- Debugging an -O2 build where variables show as optimized out.
- Running valgrind on an ASan-instrumented binary; use one or the other.
Quick quiz
Pick an answer to see if you're right and why.
Practice exercises
Try each one yourself first. Use the hint if you get stuck, then compare with the solution.
- Exercise 1easy
Write a program that dereferences a NULL pointer, run it under gdb and report the crashing line with bt.
- Exercise 2medium
A program mallocs a 100-byte buffer in a loop 10 times and never frees it. Use valgrind to confirm the exact number of bytes lost, then fix it.
- Exercise 3hard
Write a tiny program with a use-after-free, then explain each of the three stack traces ASan prints for it.
Check yourself
Answer in your head, reveal, then be honest with yourself.
Feel confident about this topic?
Frequently asked questions
- Can I use gdb on a program that is already running?
- Yes: gdb -p PID attaches to it, as long as you own the process and ptrace is allowed (some distros restrict it with kernel.yama.ptrace_scope). Detach with detach or quit and it keeps running.
- Can I use AddressSanitizer and valgrind together?
- No. ASan replaces malloc and reserves huge address ranges, which confuses valgrind. Pick one per run.
- Why does my bug disappear when I add printf?
- Printing changes timing and memory layout, which can hide memory errors and race conditions. That is a strong hint the bug is undefined behaviour; run a sanitizer instead of adding prints.