Debugging C Programs with GDB
Your program compiles, runs and prints the wrong answer. Adding printf everywhere works for small programs, but it is slow and messy. A debugger lets you pause the program at any line, look inside every variable and run it one line at a time, like watching a cricket replay in slow motion.
In this lesson you will learn to use GDB (the GNU Debugger): compile with -g, set breakpoints, step through code, print and watch variables, and use backtrace to find where a program crashed. You will fix a real bug with it.
What You Will Learn
- What a debugger is and why it beats printf debugging.
- How to compile a program for debugging.
- The most important GDB commands.
- How to find a logic bug with breakpoints, next and print.
- How to find the line of a crash with backtrace.
- Tips for debugging in an IDE.
Debugging C Programs with GDB Explained
Exam definition: Debugging is the process of finding and fixing errors (bugs) in a program. A debugger is a tool that runs a program under control so the programmer can stop it at chosen points (breakpoints), execute it statement by statement (stepping) and examine or change variables. GDB is the standard command-line debugger for C on Linux; the program must be compiled with the -g option so that GDB knows the source lines and variable names.
Memory trick: GDB is a TV remote for your program. break = mark the scene, run = play, next = next scene, step = zoom into a scene (enter a function), print = pause and read the subtitles (values), continue = play till the next mark, backtrace = "how did we get here?"
Syntax: Compiling and Starting GDB
gcc -g -O0 program.c -o program # -g: add debug info, -O0: no optimization
gdb ./program # start GDB with the program
gdb --args ./program 10 20 # start GDB and pass command line arguments
(gdb) quit # leave GDB
| Command | Short | What it does |
|---|---|---|
break main / break 12 | b | Set a breakpoint at a function or a line |
run | r | Start the program (stops at the first breakpoint) |
next | n | Run the next line; don't go inside function calls |
step | s | Run the next line; go inside a function call |
continue | c | Run until the next breakpoint |
print sum | p | Show the value of a variable or expression |
display sum | Show the value automatically after every step | |
watch sum | Stop whenever the variable changes | |
info locals | Show all local variables | |
list | l | Show the source code around the current line |
backtrace | bt | Show the chain of function calls (where a crash happened) |
finish | Run until the current function returns; show the return value | |
delete | d | Remove breakpoints |
Example 1: A Program with a Bug
This program should print the average of four marks, 75. Save it as average.c; the line numbers are used in the GDB session below.
#include <stdio.h>
int average(int a[], int n)
{
int i;
int sum = 0;
for (i = 1; i < n; i++)
sum += a[i];
return sum / n;
}
int main(void)
{
int marks[4] = {70, 80, 90, 60};
int avg = average(marks, 4);
printf("Average = %d\n", avg);
return 0;
}
Output
Average = 57
Code Explanation
- (70 + 80 + 90 + 60) / 4 = 300 / 4 = 75, but the program prints 57. There is a logic error: no compile error, no crash, just a wrong answer.
- We could stare at the code, but in a big program that doesn't scale. Instead, we pause inside
averageand look at the values with GDB. - The session below finds two bugs: the loop starts at
i = 1, soa[0](70) is skipped, andsum / nis integer division.
How to Debug It with GDB (Step by Step)
Lines starting with (gdb) are what you type; the rest is GDB's reply. Memory addresses will be different on your computer.
$ gcc -g -O0 average.c -o average
$ gdb ./average
(gdb) break average
Breakpoint 1 at 0x1151: file average.c, line 6.
(gdb) run
Starting program: /home/student/average
Breakpoint 1, average (a=0x7fffffffdf90, n=4) at average.c:6
6 int sum = 0;
(gdb) next
7 for (i = 1; i < n; i++)
(gdb) next
8 sum += a[i];
(gdb) print i
$1 = 1
(gdb) print a[0]
$2 = 70 <-- a[0] exists, but i started at 1: it is skipped!
(gdb) display sum
1: sum = 0
(gdb) next
7 for (i = 1; i < n; i++)
1: sum = 80
(gdb) next
8 sum += a[i];
1: sum = 80
(gdb) next
7 for (i = 1; i < n; i++)
1: sum = 170
(gdb) finish
Run till exit from #0 average (a=0x7fffffffdf90, n=4) at average.c:7
0x00005555555551b5 in main () at average.c:15
15 int avg = average(marks, 4);
Value returned is $3 = 57 <-- 230 / 4 = 57: integer division also loses .5
(gdb) quit
break averagepauses as soon as the function starts.nextmoves one line at a time;display sumshowssumafter every step, so you can watch it grow: 0, 80, 170, …print a[0]proves the first mark is never added.finishshows the return value, 57, and reveals the second bug (230 / 4 with integers).
Example 2: The Fixed Program
#include <stdio.h>
double average(const int a[], int n)
{
int i;
int sum = 0;
for (i = 0; i < n; i++) /* fix 1: start at index 0 */
sum += a[i];
return (double)sum / n; /* fix 2: real division */
}
int main(void)
{
int marks[4] = {70, 80, 90, 60};
double avg = average(marks, 4);
printf("Average = %.2f\n", avg);
return 0;
}
Output
Average = 75.00
- The loop now starts at 0, so all four marks are added: 300.
- The cast
(double)summakes the division real: 300 / 4 = 75.00. - The return type and
avgare nowdouble, and printf uses%.2f.
Finding a crash with backtrace
When a program crashes with "Segmentation fault", run it inside GDB. It stops at the crashing line, and backtrace shows how the program got there:
(gdb) run
Program received signal SIGSEGV, Segmentation fault.
0x0000555555555149 in set_first (p=0x0) at crash.c:5
5 *p = 10;
(gdb) backtrace
#0 set_first (p=0x0) at crash.c:5
#1 0x0000555555555171 in main () at crash.c:11
(gdb) print p
$1 = (int *) 0x0 <-- a NULL pointer was dereferenced
Read the backtrace from the top: the crash is in set_first at line 5, which was called from main at line 11 with p = NULL.
Important Points to Remember
- Compile with -g (and preferably -O0) or GDB can't show lines and variables.
- break → run → next/step → print is the basic loop.
- next runs a function call in one go; step goes inside it.
- display and watch follow a variable automatically.
- For crashes, run in GDB and use backtrace to find the line and the call chain.
- IDEs (VS Code, Code::Blocks, CLion) use GDB behind the scenes: clicking in the margin sets a breakpoint.
Common Mistakes Beginners Make
| Mistake | What happens | Fix |
|---|---|---|
Compiling without -g | "No symbol table is loaded"; no line numbers | gcc -g prog.c |
Debugging an -O2 build | Lines jump around, variables "optimized out" | Use -O0 while debugging |
Typing run before setting breakpoints | The program finishes without stopping | Set break main first |
Using step on printf | Enters library code with no source | Use next for library calls, or finish to get out |
| Forgetting to recompile after a fix | GDB shows the old program | Recompile, then run again |
Debugging with GDB Practice Questions
- What is debugging, and what is a debugger?
- Why must a program be compiled with
-gfor GDB? - What is the difference between
nextandstep? - What does
backtraceshow? - Which command stops the program whenever a variable changes?
Show answers
- Debugging is finding and fixing bugs; a debugger is a tool that runs a program under control so you can stop it, step through it and inspect variables.
-gadds debug information (source line numbers, variable and function names) to the executable.nextexecutes a function call as one step;stepenters the called function.- The chain of function calls (the call stack) that led to the current point, e.g. where a crash happened.
watch variable.
Coding Exercise
This factorial program prints 24 for 5! instead of 120. Use GDB (break factorial, display f, display i, next) to find out why, then fix it.
#include <stdio.h>
int factorial(int n)
{
int f = 1, i;
for (i = 1; i < n; i++)
f *= i;
return f;
}
int main(void)
{
printf("5! = %d\n", factorial(5));
return 0;
}
Show solution
Stepping with display i shows the loop stops when i becomes 5, so it multiplies only 1 × 2 × 3 × 4 = 24. The condition must be i <= n.
#include <stdio.h>
int factorial(int n)
{
int f = 1, i;
for (i = 1; i <= n; i++)
f *= i;
return f;
}
int main(void)
{
printf("5! = %d\n", factorial(5));
return 0;
}
5! = 120
Quick Quiz: Debugging with GDB (MCQ)
-
Which gcc option adds debugging information?
A)
-oB)-gC)-cD)-E -
Which GDB command sets a breakpoint?
A)
stopB)pauseC)breakD)halt -
Which command goes inside a function call?
A)
nextB)stepC)finishD)continue -
To see where a segmentation fault happened, use:
A)
printB)listC)backtraceD)delete -
p totalin GDB:A) Pauses the program B) Prints the value of total C) Deletes total D) Sets total to 0
Show answers
- B:
-g. - C:
break. - B:
step. - C:
backtrace. - B: prints the value of total.
Quick Revision for Exams and Interviews
Read this before your exam. The highlighted words are the answer.
Must-remember facts
| GDB | GNU Debugger for C |
|---|---|
| Compile | gcc -g -O0 |
| break / run | Set a breakpoint / start |
| next vs step | next skips over calls, step enters them |
| print / display / watch | Show / show every step / stop on change |
| backtrace | Call stack: where a crash happened |
| finish | Run to the end of the function, show the return value |
Frequently asked questions
- How do you debug a C program with GDB?
- Compile with -g, start gdb ./program, set a breakpoint, run, then use next/step and print to inspect values.
- What is a breakpoint?
- A marked line or function where the debugger pauses the program so you can examine it.
- How do you find the cause of a segmentation fault?
- Run the program in GDB; when it crashes, type backtrace to see the line and call chain, then print the pointers involved.
Remember
- GDB = the TV remote: break, run, next, step, print.
- No -g, no debugging.
Next Topic
Next lesson: Introduction to Data Structures in C. Module 16 begins: you will learn what data structures are and how to choose the right one.