Breakpoints
- C course
- Intermediate
- Lesson 95/116
- 5 min
Learn to set breakpoints and step in gdb.
Setting breakpoints
A breakpoint is a line where the program temporarily stops. In gdb you set it with break. For example break main stops at the function entry, break program.c:10 at line 10.
After stopping, continue runs to the next breakpoint. step executes one line and enters functions; next steps over function calls in one go. The distinction matters: use step to trace your own functions line by line, next to skip library calls. Breakpoints are the most powerful tool for narrowing down where a bug lives.
Breakpoints in a loop
When chasing a bug inside a loop, a breakpoint on the loop body lets you inspect each iteration. With continue you stop at every iteration.
Example program: for (int i = 0; i < 3; i++) printf("step %d\n", i);. In gdb, set a breakpoint on the loop body line and each continue advances to the next iteration. This is the fastest way to catch bugs that appear only in certain iterations. To see which iteration has the problem, inspect i with print i each time you stop.
Practice Write a looped program
Set up a for (int i = 0; i < 3; i++) loop. In the body print each iteration with printf("adım %d\n", i);. This program is suitable for setting a breakpoint on the loop body in gdb.
Starter code
#include <stdio.h>
// Write a loop from 0 to 2
// Print "adım %d\n" at each iteration
int main(void) {
return 0;
}Sample solution
#include <stdio.h>
int main(void) {
for (int i = 0; i < 3; i++) {
printf("adım %d\n", i);
}
return 0;
}Expected output
adım 0 adım 1 adım 2
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Match the gdb step commands
| Term | Meaning |
|---|---|
break |
Set breakpoint |
continue |
Run to next |
step |
Enter function |
next |
Step over call |
2 What is the difference between step and next?
- step enters functions, next steps over Correct answer
- step is slower, next is faster
- They are identical
- step only works in main
Explanation: step enters a function call; next steps over it in one move.
3 Complete the loop bound
for (int i = 0; i < ____; i++)
for (int i = 0; i < 3; i++)
Explanation: The test i < 3 yields values 0, 1, 2.