The Programming Shortcut: Debugging
Part of The Programming Shortcut, a series that teaches one programming idea per article to people who already program. This one is about debugging: finding out what a program is actually doing.
The program is right. You are wrong.
Here is the uncomfortable truth at the bottom of every bug: your program is doing what you told it to do. It isn’t confused. It didn’t misunderstand you. It followed every instruction, in order, with perfect obedience, and the result is wrong because one of your instructions doesn’t mean what you think it means.
That’s the most useful fact in this article. It means a bug is not a mystery inside the computer. It’s a gap between two things you can look at: what you believe the program does, and what it actually does. Debugging is the work of finding the spot where those two part ways.
Most people, when a program gives the wrong answer, start fixing. They change a
< to a <=, run it again, and see if the problem goes away. Sometimes it does,
and they learn nothing. Sometimes it doesn’t, and now there are two changes to
undo. Debugging starts one step earlier. Before you change anything, you find out
what is going on.
So debugging, in this article, means finding out what a program is actually doing. Fixing is the easy part that comes afterward.
We’ll use C, because C checks almost nothing on your behalf, so the gap between belief and reality can get wide, and it has
some of the oldest and sharpest tools for looking into that gap. You don’t need
to know C to follow along. If you can read a for loop in any language, you can
read every line of code here.
If you learned lux, you may have met lux trace, which runs a program and shows
the value each line changed. A debugger is the same idea with you in charge: you
choose where the program stops and what to ask it.
Compile, run, look
This article uses Linux, because that’s where the tools here are at home. On Windows, the same steps work inside WSL (the Windows Subsystem for Linux). On a Mac, the built-in debugger is LLDB, and its GDB to LLDB command map translates everything below.
You need two programs: GCC, the GNU C compiler, and GDB, the GNU debugger. On Debian or Ubuntu, one command installs both:
sudo apt install gcc gdb
(The GDB home page has the rest.)
C is a compiled language: you don’t run the source file, you run a separate
program the compiler builds from it. So every change takes three steps. Edit the
file, compile it, run what came out. Save this as words.c:
#include <stdio.h>
int count_words(const char *text) {
int count = 1;
for (int i = 0; text[i] != '\0'; i++) {
if (text[i] == ' ') {
count++;
}
}
return count;
}
int main(void) {
printf("%d\n", count_words("a b"));
}
A string in C is an array of characters ending in a zero character, written
'\0', so the loop walks the text one character at a time until it reaches the
end. The function counts the spaces and adds one. Two words, one space between
them: two. Compile and run:
gcc -std=c23 -Wall -Wextra -g -fsanitize=address,undefined -o words words.c && ./words
That’s a long line, so here it is in pieces. -std=c23 picks the current C
standard. -Wall -Wextra turns on the compiler’s warnings, which catch a lot of
mistakes before you ever run anything. -g is the one this article leans on: it
tells the compiler to keep debugging information, a map from the machine code
back to your line numbers and variable names. Without it, a debugger can only show
you raw memory addresses. -fsanitize=address,undefined turns on two
sanitizers, extra checks built into your program that catch certain memory
mistakes the moment they happen; more on those later. -o words names the
program, and && ./words runs it if the compile worked.
The program prints:
3
Two words. It says three. Good: we have a bug, and we know how to make it happen on demand.
First, make it small
Notice what the program counts. Not “hello world” or a paragraph from a book, but
"a b", with two spaces in the middle. That’s on purpose.
The first move in any debugging session is to reproduce the bug: find an input that makes it happen every time you run the program. The second move is to make that input as small as you can. Maybe you first noticed the problem on a long sentence someone pasted in. Cut it in half and try again. If the bug is still there, cut again. If it’s gone, the cause was in the half you removed, so put that half back and cut the other one. A few rounds of halving gets you from a page of text to four characters.
This matters more than it seems. A small input means a short trip through the program, and every step you watch is a step you can understand. Nobody steps through a thousand loop iterations with a clear head.
Then, before you look at anything, say what you expect to see. Out loud, or in a comment, or on a sticky note. “The loop runs four times. The count goes up once, at the space.” A prediction turns looking into a test. When what you see doesn’t match what you said, you’ve found the gap. Without a prediction you can stare at correct-looking values all afternoon and never notice which one is wrong.
Asking with print
The oldest debugging tool is the print statement. You add a line that reports what the program is doing, run it, and read.
In C, the right place for debugging output is stderr, the standard error
stream. It’s a second output channel, separate from the normal one, so your
reports don’t mix into the program’s real output, and it’s written out
immediately rather than saved up, so you still see it if the program crashes a
moment later. fprintf(stderr, ...) is how you write to it:
#include <stdio.h>
int count_words(const char *text) {
int count = 1;
for (int i = 0; text[i] != '\0'; i++) {
fprintf(stderr, "i=%d char='%c' count=%d\n", i, text[i], count);
if (text[i] == ' ') {
count++;
}
}
return count;
}
int main(void) {
printf("%d\n", count_words("a b"));
}
Compile and run it the same way. Here’s what comes out:
i=0 char='a' count=1
i=1 char=' ' count=1
i=2 char=' ' count=2
i=3 char='b' count=3
3
Compare that with the prediction. “The count goes up once, at the space.” But
there are two spaces, at i=1 and i=2, and the count went up at both. The
function doesn’t count words. It counts spaces, and it was only right when every
gap between words happened to be one space wide.
That’s the bug found. Notice how little cleverness it took. One line of output, one prediction, one comparison.
Print statements have real strengths. They work in every language, in every environment, even on a server where you can’t run anything interactive. They leave a record you can read top to bottom.
They have one big weakness: you have to decide in advance what to ask. If the output makes you wonder about a different variable, you edit, compile and run again. For a small program, fine. For a bug that takes two minutes to reproduce, each new question costs two minutes. And afterward you have to find every print you added and take it out.
Asking with a debugger
A debugger is a program that runs your program for you, and can pause it. While it’s paused, you can look at any variable, run one line, look again, and decide what to ask next. The questions don’t have to be planned. You ask them as they occur to you, while the program waits.
Take out the fprintf line, compile again, and start GDB with the program’s name:
gdb ./words
GDB prints a little banner and gives you a (gdb) prompt. Nothing has run yet.
First, tell it where to stop. A breakpoint is a spot in your code where the
debugger will pause the program. You can name a function or a line number:
(gdb) break count_words
Breakpoint 1 at 0x11c6: file words.c, line 4.
(gdb) run
Starting program: /home/you/words
Breakpoint 1, count_words (text=0x555555556060 "a b") at words.c:4
4 int count = 1;
The program started, ran until it entered count_words, and stopped. GDB shows
you the line it’s about to run, not the one it just ran: line 4 hasn’t happened
yet. It also shows the function’s arguments, so you can see the text really is
"a b". (The long number is the text’s address in memory, which you can ignore.)
Now move forward. next runs one line and stops again:
(gdb) next
5 for (int i = 0; text[i] != '\0'; i++) {
(gdb) next
6 if (text[i] == ' ') {
(gdb) print text[i]
$1 = 97 'a'
print shows the value of anything you can write in C: a variable, an array
element, a little expression. A character prints as its number and its symbol, so
97 'a' is the letter a. The $1 is GDB numbering its answers so you can refer
back to them.
Typing print after every step gets old. display asks GDB to show a value
automatically every time the program stops:
(gdb) display i
1: i = 0
(gdb) display count
2: count = 1
(gdb) next
5 for (int i = 0; text[i] != '\0'; i++) {
1: i = 0
2: count = 1
(gdb) next
6 if (text[i] == ' ') {
1: i = 1
2: count = 1
(gdb) next
7 count++;
1: i = 1
2: count = 1
(gdb) next
5 for (int i = 0; text[i] != '\0'; i++) {
1: i = 1
2: count = 2
(gdb) next
6 if (text[i] == ' ') {
1: i = 2
2: count = 2
(gdb) next
7 count++;
1: i = 2
2: count = 2
There it is again, without editing the program: line 7 runs a second time, at
i = 2, and the count is about to reach three. You watched the belief (“one
space, one new word”) fail in real time. Pressing Enter on an empty line repeats
the last command, so stepping is mostly one key.
A few more commands cover most of what you’ll do. step is like next, but when
the line calls a function, step goes into it and next runs it in one go.
continue lets the program run until it hits another breakpoint or ends.
finish runs until the current function returns, and shows you what it returned:
(gdb) finish
Run till exit from #0 count_words (text=0x555555556060 "a b") at words.c:7
0x000055555555537b in main () at words.c:14
14 printf("%d\n", count_words("a b"));
Value returned is $2 = 3
backtrace answers “how did I get here?” by listing the chain of function calls
that led to the current line, innermost first. info locals prints every local
variable at once. quit leaves.
That’s how a debugging session goes: set a breakpoint, run, step, look. When you change the
code, you compile again and type run in the same GDB session; it notices the
new program and picks it up, and your breakpoints are still there.
Stopping when something changes
Stepping line by line is fine for four characters. Real bugs hide in loops that run thousands of times, and you don’t want to press Enter thousands of times. Two kinds of stop are smarter than a plain breakpoint.
A conditional breakpoint stops only when an expression is true. break 7 if i == 2 stops at line 7 only on the trip where i is 2, and runs straight through
the others. When you know which iteration goes wrong, this takes you there
directly.
A watchpoint doesn’t care about lines at all. watch count tells GDB to stop
whenever count changes, wherever that happens, and to show you the old value and
the new one. When the question is “who is changing this variable, and when?”, a
watchpoint answers it.
Watchpoints have one surprise. A local variable only exists while its function is running, so when the function returns, GDB deletes the watchpoint and says so. You’ll see that message in the project, and it tells you something useful there.
Where C won’t help you
In most languages you’ve used, certain mistakes stop the program at the line with
the mistake. Read past the
end of a list in Python and you get an IndexError with a line number. Java, Go
and Rust stop too. JavaScript carries on, but it hands you undefined, not some
stray number from elsewhere in memory.
C doesn’t. In C, reading or writing past the end of an array is undefined behavior, the C standard’s term for things the language makes no promises about at all. The program might crash. It might carry on with whatever happened to be in memory after the array. It might write into a neighboring variable, and the wrong value shows up ten functions later, far from the line that caused it. That’s the cruelest kind of bug, because the symptom points somewhere innocent.
Here’s a small one. The loop says <= where it means <, so it reads a fourth
score from a three-score array. Save it as main.c:
#include <stdio.h>
int main(void) {
int scores[3] = {90, 85, 77};
int total = 0;
for (int i = 0; i <= 3; i++) {
total += scores[i];
}
printf("%d\n", total);
}
Built without sanitizers, this printed 255 on my machine: the real total of 252,
plus 3 from whatever sat in memory just past the array. No error, no warning, just
a slightly wrong number. On another machine it could be any number at all.
Built with the sanitizers from the compile command above, the same program stops at the line that did it:
main.c:7:24: runtime error: index 3 out of bounds for type 'int [3]'
...
==76289==ERROR: AddressSanitizer: stack-buffer-overflow on address 0x7f880350002c
READ of size 4 at 0x7f880350002c thread T0
#0 0x5592cf976415 in main main.c:7
The AddressSanitizer checks every memory access, and the UndefinedBehaviorSanitizer checks for things like this out-of-range index. Together they give back a good part of the promise C left out, at the cost of a slower program. That’s why they’re in every compile command in this article. For more on how C lays out arrays in memory, and why nothing stops you walking off the end of one, see the C article.
One more thing C takes away: when the compiler optimizes (the -O2 flag, for
example), it rearranges and removes code, and the debugger can no longer match
machine instructions to your lines. Variables show up as <optimized out> and
next jumps around. Debug with optimization off, which is GCC’s default.
Beware of the bug that goes away when you look at it. Sooner or later you’ll
add a printf, or run under GDB, and the bug will vanish. It’s tempting to call
that fixed and leave the print in. Don’t. In C, a bug that changes when unrelated
code changes is almost always undefined behavior: something is reading memory it
shouldn’t, and your print just moved what lives there. The bug is still in the
program, waiting for a different compiler or a different day. Turn the sanitizers
on, reproduce it again, and keep looking until you can point at the line.
Project: the streak that wasn’t counted
The project is a small program with a bug in it. Your job is to find the bug with GDB before you read the answer.
streak.c takes a list of daily temperatures and reports the longest rise: the
most days in a row where each day was warmer than the one before. Get the file
from projects/debugging/streak.c, or copy it from here (the full file also ends
with a block of “Try this next…” ideas):
#include <stdio.h>
#include <stdlib.h>
int longest_rise(const int *temps, int count) {
int best = 1;
int current = 1;
for (int i = 1; i < count; i++) {
if (temps[i] > temps[i - 1]) {
current++;
} else {
if (current > best) {
best = current;
}
current = 1;
}
}
return best;
}
int main(int argc, char *argv[]) {
int count = argc - 1;
int temps[100];
if (count < 1 || count > 100) {
fprintf(stderr, "usage: %s TEMP TEMP ... (1 to 100 readings)\n", argv[0]);
return 1;
}
for (int i = 0; i < count; i++) {
temps[i] = atoi(argv[i + 1]);
}
printf("longest rise, in days: %d\n", longest_rise(temps, count));
return 0;
}
main reads the temperatures from the command line (argc counts the words you
typed, argv holds them, and atoi turns each into a number) and passes them to
longest_rise. In C, an array handed to a function arrives as a pointer, the
memory address of its first element, which is why the function also needs count
to know where the array ends; the C article explains pointers properly.
Compile it and try two inputs:
$ gcc -std=c23 -Wall -Wextra -g -fsanitize=address,undefined -o streak streak.c
$ ./streak 3 4 5 1 2
longest rise, in days: 3
$ ./streak 5 1 2 3 4
longest rise, in days: 1
The first is right: 3, 4, 5 is three days of rising. The second is wrong. 1, 2, 3,
4 rises for four days, and the program says one. You have a reproduction, and
5 1 2 3 4 is already small.
Make your prediction. best starts at 1. The rise 1, 2, 3, 4 is four days long,
so somewhere during the loop, best should change to 4. Ask GDB whether it does.
--args lets you pass the temperatures along:
$ gdb --args ./streak 5 1 2 3 4
(gdb) break longest_rise
Breakpoint 1 at 0x224b: file streak.c, line 5.
(gdb) run
Starting program: /home/you/streak 5 1 2 3 4
Breakpoint 1, longest_rise (temps=0x7ffff4c00030, count=5) at streak.c:5
5 int best = 1;
(gdb) next
6 int current = 1;
(gdb) watch best
Hardware watchpoint 2: best
(gdb) continue
Continuing.
Watchpoint 2 deleted because the program has left the block in
which its expression is valid.
0x0000555555556823 in main (argc=6, argv=0x7fffffffd7f8) at streak.c:30
30 printf("longest rise, in days: %d\n", longest_rise(temps, count));
We stepped once past line 5 so best had its starting value before we watched
it. Then the program ran the whole loop, and the watchpoint never fired. It was
deleted when longest_rise returned. That’s the answer to the question we asked:
best never changed.
So the next question is what the function knew when it gave up. Clear the old
breakpoints with delete, stop at the return on line 17 instead, and run
again, saying yes to starting over:
(gdb) delete
Delete all breakpoints, watchpoints, tracepoints, and catchpoints? (y or n) y
(gdb) break 17
Breakpoint 3 at 0x55555555642c: file streak.c, line 17.
(gdb) run
The program being debugged has been started already.
Start it from the beginning? (y or n) y
Starting program: /home/you/streak 5 1 2 3 4
Breakpoint 3, longest_rise (temps=0x7ffff4c00030, count=5) at streak.c:17
17 return best;
(gdb) info locals
best = 1
current = 4
There’s the gap.
The function counted the rise perfectly: current is 4. It just never copied
that into best. Look at where the copy happens: inside the else, which only
runs when a rise ends because the temperature fell. This rise didn’t end with a
fall. It ended with the list. The loop finished, and nobody checked the last
streak.
That’s why 3 4 5 1 2 worked: its longest rise ended with a drop to 1, which
triggered the copy. The bug only shows when the longest rise is the last thing in
the list. Plenty of hand-picked test inputs would miss it.
Now you can fix it, and the fix follows from what you saw. The comparison
shouldn’t wait for the rise to end. Move it out of the else, so it runs after
every day:
if (temps[i] > temps[i - 1]) {
current++;
} else {
current = 1;
}
if (current > best) {
best = current;
}
Compile, and run both inputs again:
$ ./streak 5 1 2 3 4
longest rise, in days: 4
$ ./streak 3 4 5 1 2
longest rise, in days: 3
Then run it under GDB once more with watch best, and watch it climb from 1 to 2
to 3 to 4. Seeing the fixed program behave the way you predicted is the other half
of debugging: the gap is closed.
What’s left out
GDB can open a core dump, the snapshot of memory a crashed
program leaves behind, and show you the moment of the crash after the fact. It can
attach to a program that’s already running. It has a text interface that shows
your source code above the prompt (gdb -tui). Programs that do several things at
once have their own debugging problems, and GDB has commands for each thread.
Memory checkers like Valgrind, logging libraries, and the debuggers built into
editors all do versions of what you did here. If you use version control, git bisect applies the halving trick to your history, to find the change that
introduced a bug; the version control piece covers git.
When you’ve found a bug, a good habit is to write a small test that fails because of it, before you fix it, so you’ll hear about it if it ever comes back. The testing piece is about that.
For going further with GDB itself, the manual is Debugging with GDB, written by the people who make it. Its chapters on stopping and continuing, and on examining data, are the ones to read next.
Your turn
Pick a program you think you understand. One you wrote last month, or words.c,
or streak.c after the fix. Start it in GDB, type break main and run, and
then step through it, one line at a time, into every function it calls.
Before each step, say what the next line will do and what the values will be.
Then press Enter and see. Bring one question to it: where does my prediction
first go wrong? Expect a surprise, sooner than you’d think, in code you would
have sworn you knew. When you do, type help and look for the
command that would have shown it to you sooner.
Related
- C: arrays, pointers and memory, and why reading past the end of an array is allowed to happen
- Testing: turning a bug you’ve found into a check that keeps it from coming back
- Version control: saving and comparing your project’s history, the history
git bisectsearches
Tested with GCC 14.2 and GDB 16.3, November 2026.