Skip to content
Tutorials Center
My learning

Topics

Lesson 97 of 135 ยท Advanced C

Debugging C Programs

Learn to debug C programs - read compiler output and crashes, trace with fprintf and assert, step through code with GDB, and find memory bugs with Valgrind and sanitizers.

Every C programmer spends a large share of their time debugging. C gives you very little protection at run time: a wrong index doesn't throw an exception, it quietly overwrites another variable, and the crash may come much later in an unrelated function. Good debugging in C is therefore less about luck and more about method: reproduce the problem, narrow down where it happens, form a guess, and prove or disprove it with evidence.

This lesson walks through the whole toolbox, from the cheapest tools to the most powerful: reading compiler messages, tracing with fprintf, checking assumptions with assert, understanding crash reports, stepping through code with the GDB debugger, and catching memory errors with Valgrind and the sanitizers. You'll get the most out of it if you've read Undefined Behavior and Memory Errors, because those describe the bugs you'll be hunting.

A method that works

When a program misbehaves, resist the urge to change code at random until it works. Follow these steps instead:

  1. Reproduce it reliably. Find the exact input that triggers the bug. In our editor, put it in the Input box so every run is the same. A bug you can't reproduce, you can't confirm you've fixed.
  2. Shrink the input. Remove lines of input and code until the bug barely still happens. A ten-line program that shows the bug is far easier to reason about than a thousand-line one, and often the shrinking alone reveals the cause.
  3. Locate it. Find the first place where the program's state differs from what you expect. Print values, add asserts or use a debugger, working in halves: check the middle of the computation, then the half that's wrong, and so on.
  4. Explain it. Before you fix anything, be able to say why the bug happens. "Changing <= to < made it work" is not an explanation; "the loop wrote buf[10] in a 10-element array" is.
  5. Fix it and keep a test. Re-run the input that triggered the bug, and keep it as a test so the bug can't quietly return.

Step zero: read the compiler

The cheapest bugs to fix are the ones the compiler already found. Our editor compiles with -Wall -Wextra, and every warning deserves attention. GCC's messages follow a fixed format: main.c:12:9: warning: ... means file main.c, line 12, column 9. The first error is the one to fix first, because later errors are often caused by it. A missing semicolon or brace can produce a cascade of confusing errors a few lines further down.

Warnings that almost always point at real bugs: -Wuninitialized and -Wmaybe-uninitialized, -Wformat (a printf specifier that doesn't match its argument), -Wreturn-type (a function that can end without returning a value), -Wsign-compare, -Wsequence-point and -Wparentheses (if (x = 5)). On your own machine, add -Werror so you can't ignore them, as recommended in Best Practices.

printf debugging, done properly

Adding print statements is the oldest debugging technique and still one of the most effective. Three details make it far more useful:

  • Print to stderr, not stdout. stdout is usually buffered: when it goes to a file or a pipe, output collects in memory and is written in big chunks. If the program crashes, whatever is still in the buffer is lost, and your last trace line never appears, so you look for the bug in the wrong place. stderr is unbuffered and shows up immediately.
  • Say where you are. The predefined macros __FILE__, __LINE__ and __func__ give the location for free (see Predefined Macros and assert).
  • Make traces easy to switch off with a macro, so you don't have to delete them by hand.

First, see the buffering problem for yourself. This program prints two lines to stdout, one to stderr, and then aborts:

C Buffered output is lost in a crash

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

The program is stopped with the signal SIGABRT (our editor adds a note explaining the crash), and only the stderr line appears. Both printf lines were still waiting in the stdout buffer when abort ended the process. On a terminal, stdout is line-buffered, so you'd see them there: the same program behaves differently depending on where its output goes. That's why trace output belongs on stderr, or you call fflush(stdout) after important lines.

Now a reusable trace macro. It prints the location and a formatted message to stderr, and compiles to nothing when NDEBUG is defined, the same switch assert uses:

C A trace macro with file, line and function

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Each trace line looks like [main.c:18 digit_sum] n=4096 sum=0, so you can see exactly how the loop variables evolve. The do { ... } while (0) wrapper makes the macro behave like a single statement, which the Macros lesson explains. __VA_ARGS__ forwards all the arguments to fprintf.

Tracing to find a real bug

Here's a function with a bug. It should return the largest value in an array, but for one of the test arrays it gives the wrong answer. Run it, then read the trace to see why.

C Find the bug with a trace

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

The trace for the second array shows best=0 on every line: no element is ever greater than 0, so the function returns 0, a value that isn't even in the array. The starting value is the bug. The fix is int best = values[0]; and starting the loop at i = 1 (with a check that count > 0). The trace made the cause obvious in seconds.

assert: make the program check itself

An assertion states something that must be true if the program is correct. assert(expression) from <assert.h> does nothing when the expression is true. When it's false, it prints the expression, file, line and function to stderr and calls abort. Assertions turn silent wrong results into loud, precise failures right where an assumption broke.

C An assertion catches a bad argument

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

The first call prints average = 80.00. The second stops the program with a message like main.c:7: average: Assertion `count > 0' failed. (glibc puts the program name in front; ours shows as binary). Without the assert, the division would produce nan and the bad value would travel on through the program.

Use assert for programmer errors: conditions that can only be false if the code has a bug, such as a null pointer passed to a function that requires one, or an index out of range. Don't use it for things that can legitimately fail at run time (a missing file, bad user input, malloc returning NULL); handle those with real error handling. Release builds are usually compiled with -DNDEBUG, which removes every assert, so never put code with side effects inside one: assert(fgets(line, sizeof line, stdin)) would stop reading input in a release build.

Reading crash output

When a C program crashes, the operating system kills it with a signal. Knowing what each one usually means is half the diagnosis:

Signal Usual cause
SIGSEGV (segmentation fault) Dereferencing a null, dangling or wild pointer; writing far past an array; writing to a string literal; infinite recursion (stack overflow)
SIGABRT (abort) A failed assert, or the C library detected corrupted memory, e.g. "free(): double free detected" or "malloc(): corrupted top size"
SIGFPE (floating-point exception) Integer division by zero, or INT_MIN / -1 (despite the name, not floating point)
SIGBUS Misaligned access or a memory-mapped file that shrank (mostly on non-x86 systems)
SIGKILL Killed from outside, for example for using too much memory or time

In a shell, a crashed program's exit status is 128 plus the signal number: 139 means SIGSEGV (11), 134 means SIGABRT (6). Our editor turns signals into a short plain-language note under the output.

A crash tells you what went wrong, but rarely where the bug is. A double-free message appears at the second free, while the bug may be the code that forgot the pointer was already freed. To find the line that caused the problem, use a debugger or a sanitizer.

Using GDB

A debugger lets you pause a running program, look at every variable, step line by line, and see the chain of function calls that led to the current point. GDB is the standard debugger on Linux; LLDB (macOS, Clang) uses almost identical commands, and Visual Studio and VS Code put a graphical front end on the same ideas. Debuggers can't run inside our online editor, so here's a typical session on your own machine.

Compile with debug information and without optimization, so lines and variables map cleanly to the machine code:

Terminal
gcc -g -O0 -Wall -Wextra main.c -o app
gdb ./app

Suppose app crashes with a segmentation fault. A session might look like this (your addresses will differ):

TEXT
(gdb) run
Program received signal SIGSEGV, Segmentation fault.
0x0000555555555189 in count_words (text=0x0) at main.c:8
8           while (*text != '\0') {
(gdb) backtrace
#0  count_words (text=0x0) at main.c:8
#1  0x00005555555551f4 in process_line (line=0x7fffffffe0a0 "") at main.c:21
#2  0x0000555555555256 in main () at main.c:30
(gdb) frame 1
#1  0x00005555555551f4 in process_line (line=0x7fffffffe0a0 "") at main.c:21
21          int words = count_words(strtok(line, "\n"));
(gdb) print line
$1 = 0x7fffffffe0a0 ""
(gdb) quit

The backtrace answers "how did we get here?": main called process_line, which called count_words with text=0x0, a null pointer. Moving up one frame shows the cause: on an empty line, strtok returns NULL, and the code passed that straight on. Two commands found a bug that might take an hour of reading.

The commands you'll use most:

Command (short form) What it does
run (r) Start the program; run < input.txt feeds it input
break main.c:21 (b) Stop when line 21 is reached; break count_words stops at a function
next (n) Run the current line, stepping over function calls
step (s) Run the current line, stepping into function calls
continue (c) Run until the next breakpoint
finish Run until the current function returns and show its return value
print expr (p) Show a variable or expression: p count, p *node, p arr[3], p *arr@5 (5 elements)
display expr Print the expression after every step
info locals Show all local variables in the current frame
backtrace (bt) Show the call stack; frame N selects a frame
watch var Stop whenever var changes, perfect for "who overwrote this?"
break 21 if i == 99 A conditional breakpoint

watch deserves special mention. When a variable mysteriously changes value, set a watchpoint on it and continue: GDB stops at the exact line that modified it, even if that line is an out-of-bounds write in a completely different function.

Tip: Programs that crash without you can be examined afterwards from a core dump. Run ulimit -c unlimited before the program, then gdb ./app core (the file name depends on the system; on many Linux distributions coredumpctl gdb opens the latest one). bt then shows where it died.

Valgrind and the sanitizers

Memory errors are the hardest C bugs, because the moment of the mistake and the moment of the symptom are far apart. Two kinds of tools catch them at the moment they happen.

AddressSanitizer (ASan) and UndefinedBehaviorSanitizer (UBSan) are built into GCC and Clang. You recompile with extra checks, and the program stops with a detailed report at the first bad access:

Terminal
gcc -g -O1 -fsanitize=address,undefined -fno-omit-frame-pointer main.c -o app
./app

A report for an out-of-bounds write looks roughly like this (shortened):

TEXT
==4120==ERROR: AddressSanitizer: heap-buffer-overflow on address 0x502000000038
WRITE of size 4 at 0x502000000038 thread T0
    #0 0x401a2b in fill_table main.c:14
    #1 0x401b07 in main main.c:25
0x502000000038 is located 0 bytes after 40-byte region [0x502000000010,0x502000000038)
allocated by thread T0 here:
    #0 0x7f3c2d in malloc
    #1 0x401ae1 in main main.c:23

Read it top to bottom: the kind of error (heap-buffer-overflow), the access (a 4-byte write, one int), where it happened (fill_table, line 14), and the block it missed: a 40-byte region (ten ints) allocated at line 23, with the write landing right after its end. That's a classic <= loop bound. ASan also reports use-after-free, double free, stack buffer overflows and, at exit, memory leaks. UBSan reports signed overflow, bad shifts, null pointer use and misaligned access with a runtime error: line naming the file and line.

Valgrind runs your unmodified program on a simulated CPU and checks every memory access. It's slower (often 20 to 50 times) but needs no recompilation, which makes it handy for checking leaks:

Terminal
valgrind --leak-check=full ./app

At the end it prints a leak summary such as "definitely lost: 64 bytes in 2 blocks", with the call stack of each leaked allocation. Errors like "Invalid read of size 4" and "Conditional jump or move depends on uninitialised value(s)" point at the exact line. Valgrind runs on Linux (and some other Unix systems); on Windows, ASan is available in both MSVC and Clang.

Make sanitizer builds part of your routine: run your tests under -fsanitize=address,undefined regularly, not just when something is already broken.

Other techniques worth knowing

  • Rubber duck debugging. Explain the code line by line, out loud, to someone or something. Saying "and then this loop runs count times..." is often the moment you notice it runs count + 1 times.
  • Bisecting changes. If it worked yesterday, git bisect finds the exact commit that broke it by binary search.
  • Check invariants. Write a function that verifies a data structure (a list's length matches its nodes, a tree is ordered) and call it after every operation while debugging, as in Linked Lists.
  • Fresh compiler, different optimization. If a bug appears only with -O2, it's almost always undefined behavior that the optimizer exploited, not a compiler bug.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. A program prints a trace with printf and then crashes, but the trace never appears. What's the most likely reason?

    When stdout goes to a pipe or file, it is fully buffered. Write traces to stderr or call fflush(stdout).
  2. 2. What happens when assert(count > 0) runs with count equal to 0 (and NDEBUG is not defined)?

    A failed assert writes a diagnostic to stderr and calls abort, which raises SIGABRT.
  3. 3. Which use of assert is a mistake?

    With -DNDEBUG the whole expression disappears, so the program would stop reading input. Never put needed side effects in an assert, and don't use assert for input errors.
  4. 4. In GDB, which command shows the chain of function calls that led to the current line?

    backtrace (bt) lists every active frame from the current function down to main.
  5. 5. A program crashes with SIGFPE. What is the most likely cause?

    Despite its name, SIGFPE on x86 is most often an integer division by zero (or INT_MIN / -1).

Summary

  • Debug with a method: reproduce, shrink, locate, explain, then fix and keep a test.
  • Fix compiler warnings first; -Wall -Wextra -Werror finds many bugs for free.
  • Trace to stderr (unbuffered) with __FILE__, __LINE__ and __func__, behind a macro you can turn off.
  • assert checks programmer assumptions and aborts with a precise message; it disappears with NDEBUG, so no side effects inside.
  • Signals tell you the kind of crash: SIGSEGV bad memory access, SIGABRT abort or heap corruption, SIGFPE integer division by zero.
  • GDB (-g -O0): break, run, next, step, print, backtrace, watch.
  • AddressSanitizer, UBSan and Valgrind catch memory errors and UB at the moment they happen.

Next: Modern C: C99 to C23