Setting breakpoints with break
What you'll learn: How to pause your program at specific lines using the break command so you can inspect its behavior.
When you run a program normally, it rushes from start to finish like a high-speed train. If there is a bug, the train crashes, and you’re left looking at a pile of wreckage, wondering where things went wrong. Debugging with GDB allows you to place "stop signs" along the tracks. In GDB, these stop signs are called breakpoints.
The break command
A breakpoint tells GDB: "Run the program until you hit this specific line, then freeze everything and wait for my instructions." This is the most powerful tool in your debugging kit because it lets you stop time right before a suspected error occurs.
To set a breakpoint, you use the break command (or just b for short) followed by the line number.
#include <stdio.h>
int main() {
int x = 10;
int y = 0;
printf("Starting calculation...\n");
x = x + 5; // Line 8
y = x * 2; // Line 9
printf("Result: %d\n", y);
return 0;
}
If you want to stop the program before it calculates y, you would open the compiled file in GDB and type:
break 9
GDB will confirm that it has set "Breakpoint 1" at that location. When you type run, the program will execute lines 5 through 8, then suddenly pause. The computer is now in a state of suspended animation, allowing you to check if x actually equals 15 before the next step happens.
Where to break?
You don't just have to use line numbers. If you have a large program with many functions, you can tell GDB to stop at the very beginning of a function by typing the function's name:
break main
This is like setting a stop sign at the entrance of a town. As soon as the main function starts, the program will pause, giving you a clean slate to begin your investigation.
Key takeaway
Use break [line number] or break [function name] to pause your program's execution at a specific spot for inspection.