I. What Are Debuggers and Breakpoint Debugging?
1. What Is a Debugger?
A debugger is a software tool used to inspect and control the execution of a program.
It enables developers to observe the internal state of a program at runtime and to pause or control program execution under specific conditions.
Debuggers typically provide the following capabilities:
- Set and manage breakpoints.
- Step through code.
- View the values of variables and expressions.
- Inspect the call stack.
- Observe memory and object state.
- Modify some variable values.
- Catch exceptions and program crashes.
- Analyze thread and concurrent execution states.
Common debuggers include:
| Debugger | Primary use |
|---|---|
| GDB | Debugging native programs such as C and C++ |
| LLDB | Debugging programs such as C, C++, Objective-C, and Swift |
| Visual Studio Debugger | Debugging Windows, .NET, and C++ programs |
| IntelliJ IDEA Debugger | Debugging JVM programs such as Java and Kotlin |
| PyCharm Debugger | Debugging Python programs |
| Chrome DevTools | Debugging JavaScript and front-end pages |
| Node.js Inspector | Debugging Node.js programs |
| Delve | Debugging Go programs |
2. What Is Breakpoint Debugging?
Breakpoint debugging is a debugging approach in which breakpoints are set at specific locations in code so that the program pauses when execution reaches the designated location, allowing the program state to be inspected.
For example:
def calculate_total(price, quantity):
total = price * quantity
discount = 10
final_price = total - discount
return final_price
result = calculate_total(100, 3)
print(result)
If a breakpoint is set on the following line:
final_price = total - discount
Program execution pauses when it reaches that location.
At this point, you can inspect:
price = 100
quantity = 3
total = 300
discount = 10
The developer can observe whether the variables match expectations and then decide whether to continue execution or step through the subsequent code.
3. The Relationship Between a Debugger and Breakpoint Debugging
A debugger is a tool, while breakpoint debugging is a way of using the debugger to analyze a program.
| Comparison dimension | Debugger | Breakpoint debugging |
|---|---|---|
| Nature | Software tool | Debugging method |
| Main role | Control and observe program execution | Pause the program at a specified location |
| Core capabilities | Breakpoints, single-stepping, variables, call stack, etc. | Set breakpoints, pause, inspect state |
| Scope of use | Program development and fault analysis | Locate problems in specific code paths |
| Typical tools | GDB, LLDB, IDE debuggers | Regular breakpoints, conditional breakpoints, etc. |
II. Basic Working Principles of a Debugger
A debugger does not simply insert a pause instruction into the code. It needs to work in coordination with the compiler, runtime, operating system, and processor.
Debugging mechanisms differ significantly across languages and execution environments.
1. Correspondence Between Source Code and Executable Instructions
A debugger usually needs to know which machine instructions or runtime instructions correspond to a given line of source code.
For example, in C++:
int calculate(int a, int b) {
int result = a + b;
return result;
}
The compiler converts source code into machine instructions.
Debug information can record:
- Source file name.
- Source code line numbers.
- Mapping between variables and registers or memory locations.
- Function and symbol information.
- Type information.
- Information related to inline functions.
In GCC and Clang, common debugging compilation options are:
g++ -g -O0 main.cpp -o app
Among them:
-g: Generate debug information.-O0: Disable most optimizations for easier debugging.main.cpp: Source code file.app: Generated executable file.
Debug information usually does not change the program logic, but it increases the size of the executable file or debug symbol file.
2. The Role of Debug Information
After the compiler generates machine code, variables and statements in the source code do not necessarily correspond one-to-one with machine instructions.
For example:
```cpp int add(int a, int b) { int result = a + b; return result; } ```After optimization, the compiler may compute and return the result directly using registers, without allocating a separate memory location for result.
This means:
- Some variables may be optimized away.
- Multiple lines of source code may correspond to the same machine instructions.
- The execution order of machine instructions may differ from the source code order.
- Some variables may not be readable by the debugger at a particular execution position.
Therefore, the source code locations and variable values shown by the debugger are a mapping of the running state based on debug information, and they cannot necessarily fully reconstruct the abstract execution of the source code.
3. How the debugger cooperates with the operating system
In native programs, the debugger usually controls the target process through debugging interfaces provided by the operating system.
Taking Linux as an example, GDB can use mechanisms such as ptrace to:
- Attach to the target process.
- Suspend and resume the process.
- Read register state.
- Inspect the target process's memory.
- Set and handle breakpoints.
- Obtain thread execution state.
A typical debugging process:
flowchart TD
A["Start debugger"] --> B["Load target program"]
B --> C["Read symbols and debug info"]
C --> D["Create or attach to target process"]
D --> E["Set breakpoints"]
E --> F["Resume program execution"]
F --> G{"Breakpoint hit?"}
G -->|"No"| F
G -->|"Yes"| H["Suspend target thread or process"]
H --> I["Read register and memory state"]
I --> J["Inspect variables and call stack"]
J --> K{"Next action"}
K -->|"Continue"| F
K -->|"Step"| L["Execute next instruction or source statement"]
L --> I
K -->|"End"| M["Terminate debugging"]
style A fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style B fill:#E5F4EC,stroke:#A3CBB5,color:#334155
style C fill:#F3EDFC,stroke:#C4B2E3,color:#334155
style D fill:#E8EDF2,stroke:#B8C3CE,color:#334155
style E fill:#FFF5DE,stroke:#E8D29A,color:#334155
style F fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style G fill:#FFF5DE,stroke:#E8D29A,color:#334155
style H fill:#E5F4EC,stroke:#A3CBB5,color:#334155
style I fill:#F3EDFC,stroke:#C4B2E3,color:#334155
style J fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style K fill:#FFF5DE,stroke:#E8D29A,color:#334155
style L fill:#E5F4EC,stroke:#A3CBB5,color:#334155
style M fill:#E8EDF2,stroke:#B8C3CE,color:#334155
linkStyle default stroke:#A3B8AC,stroke-width:1.5px
Note that operating system debugging interfaces are not identical. Linux, Windows, and macOS use different mechanisms for process control, exception handling, and debugging.
4. Debugging mechanisms in different languages
| Language or runtime | Common debugging mechanisms | Debugging characteristics |
|---|---|---|
| C/C++ | GDB, LLDB | Operating system process debugging, machine instruction and memory inspection |
| Java | JVM Debug Interface (JVMTI/JDWP family) | Debugging capabilities provided by the virtual machine |
| Python | sys.settrace(), bdb, debugger interfaces |
Tracks interpreter execution events |
| JavaScript | Chrome DevTools Protocol | Controls execution through a runtime debugging protocol |
| Node.js | Inspector Protocol | Debugs breakpoints, call stacks, and asynchronous tasks |
| Go | Delve | Combines the Go Runtime with debug information |
| .NET | CLR debugging interface | Runtime-level debugging capabilities |
Different languages do not necessarily use the same underlying mechanisms, but the goal is basically the same: associate source code locations with runtime state, and provide execution control capabilities.
III. Types of Breakpoints
Breakpoints are the most commonly used tool in the debugging process, but ordinary breakpoints are not the only kind.
1. Line Breakpoint
A line breakpoint is used to pause the program at a specified source code line.
For example:
def divide(a, b):
result = a / b
return result
value = divide(10, 2)
print(value)
You can set a breakpoint on:
result = a / b
this line.
When the program reaches this point, it pauses, and the developer can inspect the values of a and b.
Use cases:
- Check whether a certain piece of code is executed.
- Observe variable changes.
- Analyze the program execution order.
- Locate where an error occurs.
2. Conditional Breakpoint
A conditional breakpoint pauses the program only when the specified condition is true.
For example:
for i in range(1000):
result = i * 2
print(result)
If you only care about the case where i == 500, you can set a conditional breakpoint:
i == 500
This prevents the program from pausing on every loop iteration.
Use cases:
- Specific data in a loop.
- Anomalous requests among a large number of requests.
- A specific user or business state.
- Issues triggered when a certain boundary condition occurs.
Conditional breakpoints usually require evaluating the condition expression, so complex conditions may increase debugging overhead.
3. Hit Count Breakpoint
A hit count breakpoint decides whether to pause based on the number of times the breakpoint has been hit.
For example:
Pause on the 100th hit
It is suitable for:
- Troubleshooting cumulative issues in loops.
- Locating anomalies that appear after a specific number of times.
- Analyzing repeated call behavior.
Different IDEs may compare hit counts in different ways, such as equal to a specified number, greater than a specified number, or satisfying some counting condition.
4. Function Breakpoint
A function breakpoint is set directly on a function rather than on a line of source code.
For example:
void processOrder(int orderId) {
// ...
}
You can set a breakpoint at the entry of the processOrder function.
Each time execution enters the function, the debugger can pause the program.
Use cases:
- The function call path is unclear.
- The function is called by multiple modules.
- You need to inspect function parameters.
- You need to observe the execution of a specific API.
5. Exception Breakpoint
Exception breakpoints are used to pause execution when the program throws an exception or a specific exception event occurs.
For example, in Java:
public class Main {
public static void main(String[] args) {
int result = 10 / 0;
System.out.println(result);
}
}
If you set an ArithmeticException exception breakpoint, the debugger can pause the program when the exception is thrown.
Exception breakpoints can usually be set to:
- Pause on caught exceptions.
- Pause on uncaught exceptions.
- Pause on a specified exception type.
This helps locate where the exception first occurs, rather than only looking at the final exception stack.
6. Data Breakpoint
Data breakpoints are used to monitor changes to a specific memory location or variable.
For example:
int balance = 1000;
If you need to know where balance is modified, you can set a data breakpoint on it.
When the monitored data is accessed or modified in a way that meets the condition, the debugger pauses the program.
Data breakpoints may be implemented in native debuggers using processor hardware debug registers.
However, they have limitations:
- The number of hardware watchpoints is limited.
- The length and alignment of monitored data may be restricted.
- Some variables do not have stable memory addresses after optimization.
- Not all debuggers and runtimes support the same data breakpoint capabilities.
7. Logpoint
A logpoint is a debugging feature that outputs specified information without pausing the program.
For example, to log in a loop:
Current order ID: 12345
It is suitable for:
- Scenarios where it is inconvenient to pause the program.
- Observing high-frequency execution paths.
- Debugging asynchronous code.
- Reducing the impact of ordinary breakpoints on program execution timing.
Logpoints are usually provided by IDEs or debuggers and are not necessarily a native capability of all language runtimes.
8. Comparison of Breakpoint Types
| Breakpoint Type | Trigger Condition | Main Purpose |
|---|---|---|
| Ordinary breakpoint | Execution reaches the specified location | Inspect program state |
| Conditional breakpoint | A conditional expression evaluates to true | Locate specific data |
| Hit count breakpoint | The hit count meets a condition | Investigate repeated-execution issues |
| Function breakpoint | Entering a specified function | Trace function calls |
| Exception breakpoint | A specified exception is thrown | Locate the source of an exception |
| Data breakpoint | Specific data is accessed or modified | Track variable changes |
| Logpoint | Execution reaches the specified location | Record runtime information without stopping |
IV. Single-Step Execution Mechanism
Breakpoints are responsible for pausing the program, while single-stepping is used to control how the program runs next.
Common single-step operations include Step Over, Step Into, and Step Out.
1. Step Over: Single-Step Over
Step Over means executing the current statement without entering the function called by that statement.
For example:
def calculate():
return 10 + 20
result = calculate()
print(result)
If paused at:
result = calculate()
After executing Step Over:
calculate()is executed in full.- The debugger does not enter the
calculate()function. - The program pauses near the next debuggable statement.
This is suitable when you do not need to analyze the internal logic of a function and only want to observe the result of the function call.
2. Step Into: Single-Step Into
Step Into means entering the function called by the current statement.
For example:
result = calculate()
After executing Step Into, the debugger enters the calculate() function and continues to inspect its internal execution process.
Suitable for:
- Investigating errors inside a function.
- Analyzing parameter passing.
- Checking intermediate calculation results.
- Tracing complex call chains.
3. Step Out: Single-Step Out
Step Out means continuing to execute the current function until it returns to the caller.
For example:
def calculate():
a = 10
b = 20
return a + b
def main():
result = calculate()
print(result)
If currently paused inside calculate(), after executing Step Out the debugger runs to the function's return point and returns to near the call site in main().
Suitable for:
- You have finished inspecting the current function.
- You no longer need to view the internal implementation line by line.
- You want to quickly return to the upper-level calling logic.
4. Single-Step Execution Comparison
| Operation | Chinese Meaning | Execution Behavior |
|---|---|---|
| Continue | Continue running | Run to the next breakpoint or until the program ends |
| Step Over | Single-step over | Execute the current statement without entering ordinary function calls |
| Step Into | Single-step into | Attempt to enter the function called by the current statement |
| Step Out | Single-step out | Execute until the current function returns |
| Run to Cursor | Run to cursor | Execute to the specified code location |
| Pause | Pause | Request to pause the running program |
Note that whether Step Into actually enters a function may be affected by debug information, library code filtering, asynchronous execution mechanisms, and runtime implementation.
5. Single-Step Execution Flow
flowchart TD
A["Breakpoint hit"] --> B["Pause execution"]
B --> C["Inspect current variables and call stack"]
C --> D{"Select execution action"}
D -->|"Step Over"| E["Execute current statement"]
D -->|"Step Into"| F["Enter the function"]
D -->|"Step Out"| G["Execute current function until it returns"]
D -->|"Continue"| H["Continue running program"]
E --> I["Update debug state"]
F --> I
G --> I
I --> J{"Reached a new breakpoint?"}
J -->|"Yes"| B
J -->|"No"| H
H --> K["Continue execution"]
style A fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style B fill:#E5F4EC,stroke:#A3CBB5,color:#334155
style C fill:#F3EDFC,stroke:#C4B2E3,color:#334155
style D fill:#FFF5DE,stroke:#E8D29A,color:#334155
style E fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style F fill:#E5F4EC,stroke:#A3CBB5,color:#334155
style G fill:#F3EDFC,stroke:#C4B2E3,color:#334155
style H fill:#E8EDF2,stroke:#B8C3CE,color:#334155
style I fill:#E5F4EC,stroke:#A3CBB5,color:#334155
style J fill:#FFF5DE,stroke:#E8D29A,color:#334155
style K fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
linkStyle default stroke:#A3B8AC,stroke-width:1.5px
V. Variable Inspection and Expression Evaluation
One of the most important benefits of breakpoint debugging is observing the state of data while the program runs.
1. Variables Window (Variables)
The Variables window shows the variables in the current scope and their values.
For example:
def calculate_price(price, quantity, discount):
total = price * quantity
final_price = total - discount
return final_price
If you pause before final_price is calculated, you can see:
price = 100
quantity = 3
discount = 10
total = 300
This helps determine whether the problem comes from:
- Incorrect input parameters.
- An error in an intermediate calculation.
- State being modified unexpectedly.
- Incorrect variable initialization.
2. Watch: Watch Expressions
Watch is used to continuously observe specified variables or expressions.
For example:
price * quantity
total - discount
Each time the program pauses, the debugger can recalculate these expressions and display the results.
Watch is particularly suitable for:
- Complex object properties.
- Deeply nested data.
- Key business calculations.
- Relationships between multiple variables.
However, expression evaluation is not always completely free of side effects.
In some languages or debuggers, evaluation may call methods, trigger property accessors, or execute other logic. Therefore, debug expressions should be kept as simple and read-only as possible.
3. Evaluate Expression: Expression Evaluation
Expression evaluation allows developers to manually execute expressions while paused.
For example:
user.age
len(items)
price * quantity
It helps developers quickly validate hypotheses.
However, note the following:
- Expressions may read or modify object state.
- Some method calls may have side effects.
- Evaluation may throw exceptions.
- The debugger may be unable to evaluate variables that have been optimized away.
- During remote debugging, expression evaluation may be subject to permission restrictions.
4. Modifying Variable Values
Many debuggers allow variables to be modified while paused.
For example:
discount = 20
Developers can temporarily modify a variable, then continue execution and observe subsequent behavior.
Applicable scenarios:
- Validating boundary conditions.
- Testing exception branches.
- Checking the impact of a certain state on the result.
- Temporarily bypassing unrelated logic.
However, modifying a variable value only changes the runtime state in the current debugging session; it does not mean the source code has been modified.
In some languages, modifying local variables may also be constrained by compiler optimizations, variable location, and runtime limitations.
Six. Call Stack and Function Call Analysis
When a program executes a function call, a chain of call relationships is formed.
The call stack records the hierarchy of function calls within the current thread or execution context.
1. What Is a Call Stack?
For example:
def function_c():
print("C")
def function_b():
function_c()
def function_a():
function_b()
function_a()
When function_c() executes, the call relationship is:
function_a()
└── function_b()
└── function_c()
If the program pauses inside function_c(), the call stack can typically show:
function_c
function_b
function_a
<module>
This means the current execution position is in function_c, which was called by function_b, and function_b was in turn called by function_a.
2. Stack Frame
A function call typically creates or maintains a corresponding execution context.
In traditional native calling conventions, a stack frame may contain:
- The return address.
- Saved registers.
- Local variables.
- Function arguments.
- Location information needed for debugging.
However, the exact layout depends on the processor architecture, compiler, calling convention, and optimization strategy.
Not all language runtimes implement stack frames in exactly the same way.
For example, the Java Virtual Machine uses its own runtime stack frame model, and the Python interpreter has its own execution frame structure.
3. The Value of Examining the Call Stack
The call stack helps developers answer questions such as:
- Where was the current code called from?
- Which function passed in the wrong argument?
- Is there a recursive call?
- Has an unexpected function nesting occurred?
- Where did the exception originally arise?
- Which business path led to the current state?
In complex projects, the call stack is often more valuable than examining a single line of code on its own.
4. The Relationship Between the Call Stack and Program Execution
flowchart TD
A["main()"] --> B["service()"]
B --> C["repository()"]
C --> D["database_query()"]
D --> E["Breakpoint hit"]
E --> F["Inspect the current call stack"]
F --> G["Analyze the function call path"]
G --> H["Locate the source of the problem"]
style A fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style B fill:#E5F4EC,stroke:#A3CBB5,color:#334155
style C fill:#F3EDFC,stroke:#C4B2E3,color:#334155
style D fill:#FFF5DE,stroke:#E8D29A,color:#334155
style E fill:#FBE9E9,stroke:#D9AAAA,color:#334155
style F fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style G fill:#E5F4EC,stroke:#A3CBB5,color:#334155
style H fill:#F3EDFC,stroke:#C4B2E3,color:#334155
linkStyle default stroke:#A3B8AC,stroke-width:1.5px
Seven. Debuggers and Exception Handling
Exception breakpoints are an important means of locating program errors.
Merely looking at where an exception finally occurs is often not enough to find the real source of the problem.
1. Where an Exception Is Thrown vs. Where It Is Handled
For example, in Java:
public class Main {
public static void main(String[] args) {
try {
process();
} catch (Exception e) {
System.out.println("处理失败");
}
}
static void process() {
int value = 10 / 0;
}
}
The exception is actually generated at:
int value = 10 / 0;
But the place where it is ultimately caught is in main().
If you set an ordinary breakpoint only in the exception-handling code, you may not notice in time where the exception first arose.
Exception breakpoints can help developers pause the program at the moment an exception is thrown.
2. First-Chance Exception vs. Uncaught Exception
In some debugging environments, exception breakpoints can distinguish between different exception stages.
- First-Chance Exception: Triggered when an exception is first observed by the runtime or debugging mechanism.
- Uncaught Exception: The exception is not handled normally by the program and ultimately escapes the relevant handling scope.
The specific definitions and triggering behavior of the two depend on the language runtime and debugger.
For example, some debuggers can pause before an exception is caught, or only pause when an exception is not caught.
3. Exception Debugging Workflow
flowchart TD
A["Program execution"] --> B["Exception occurs"]
B --> C["Debugger catches exception event"]
C --> D{"Does exception breakpoint match?"}
D -->|"Yes"| E["Pause program"]
D -->|"No"| F["Continue exception handling flow"]
E --> G["Inspect exception type and message"]
G --> H["View call stack"]
H --> I["Locate exception origin"]
I --> J["Analyze inputs and program state"]
J --> K["Fix the cause of the exception"]
F --> L["Enter exception handling logic"]
style A fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style B fill:#FBE9E9,stroke:#D9AAAA,color:#334155
style C fill:#F3EDFC,stroke:#C4B2E3,color:#334155
style D fill:#FFF5DE,stroke:#E8D29A,color:#334155
style E fill:#E5F4EC,stroke:#A3CBB5,color:#334155
style F fill:#E8EDF2,stroke:#B8C3CE,color:#334155
style G fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style H fill:#F3EDFC,stroke:#C4B2E3,color:#334155
style I fill:#E5F4EC,stroke:#A3CBB5,color:#334155
style J fill:#FFF5DE,stroke:#E8D29A,color:#334155
style K fill:#E5F4EC,stroke:#A3CBB5,color:#334155
style L fill:#E8EDF2,stroke:#B8C3CE,color:#334155
linkStyle default stroke:#A3B8AC,stroke-width:1.5px
VIII. Common Debugger Usage
Different languages and development environments provide different debugging tools.
1. GDB: C/C++ Debugger
GDB is the GNU Debugger, commonly used to debug native programs such as C and C++ programs.
Compile the program:
g++ -g -O0 main.cpp -o app
Start debugging:
gdb ./app
Common commands:
| Command | Purpose |
|---|---|
break main |
Set a breakpoint at the main function |
break 10 |
Set a breakpoint at line 10 in the current source file |
run |
Start the program |
continue |
Continue execution |
next |
Step over function calls |
step |
Step into a function |
finish |
Execute until the current function returns |
print x |
Inspect variable x |
display x |
Automatically display x each time execution pauses |
backtrace |
Inspect the call stack |
info locals |
Inspect local variables of the current function |
info breakpoints |
Inspect breakpoints |
delete |
Delete breakpoints |
quit |
Quit GDB |
Example:
gdb ./app
After entering GDB:
break main
run
next
print x
backtrace
continue
If the program is already running, you can also use GDB to attach to the process:
gdb -p 12345
Here, 12345 is the PID of the target process.
2. LLDB: Modern Native Program Debugger
LLDB is the debugger in the LLVM project and is commonly used for programs written in C, C++, Objective-C, Swift, and other languages.
Start it with:
lldb ./app
Common commands:
| Command | Purpose |
|---|---|
breakpoint set --name main |
Set a breakpoint at the main function |
run |
Start the program |
continue |
Continue execution |
next |
Step over |
step |
Step into |
finish |
Run until the current function returns |
frame variable |
View variables in the current stack frame |
thread backtrace |
View the thread call stack |
breakpoint list |
View breakpoints |
GDB and LLDB commands are somewhat similar, but their syntax is not completely identical.
3. Python: Debugging with pdb
Python has a built-in pdb debugger.
Example:
def calculate(a, b):
result = a * b
return result
value = calculate(10, 20)
print(value)
Set a breakpoint in the code:
import pdb
def calculate(a, b):
pdb.set_trace()
result = a * b
return result
print(calculate(10, 20))
When execution reaches pdb.set_trace(), it enters interactive debugging mode.
Common commands:
| Command | Purpose |
|---|---|
n |
Execute the next line without entering functions |
s |
Step into |
c |
Continue execution |
r |
Run until the current function returns |
p expression |
Print the expression |
l |
List nearby source code |
w |
View the call stack |
b |
Set a breakpoint |
q |
Quit debugging |
You can also use:
breakpoint()
Python calls the default debugger according to the current debugging configuration; by default, it usually enters pdb.
4. Java: Debugging with IntelliJ IDEA
IntelliJ IDEA provides a visual debugger.
Typical operations:
- Click in the line number area to set a breakpoint.
- Start the program with Debug.
- The program pauses automatically when execution reaches a breakpoint.
- View variables in the Variables window.
- View the call stack in the Frames window.
- Use Step Over, Step Into, and Step Out to control execution.
- Use Evaluate Expression to evaluate expressions.
Java debugging is usually based on the debugging capabilities provided by the JVM.