General steps for debugging a program using GDB:
First step: Compile the program (-G parameter tells the compiler to generate debug information)
>GCC test.c-g
Step Two: Run GDB
>gdb A.exe
The third step: Check the source, l list the first 10 lines of code, the letter L is the abbreviation of the list, note: Here "(GDB)" is the GDB prompt, not what we typed manually.
(GDB) L
Fourth step: Add a breakpoint (the letter B is the abbreviation for break), here is an example of adding a breakpoint in line fourth.
(GDB) B 4
Fifth Step: Execute (the letter R is the abbreviation of run), because the previous B command set the breakpoint on line 4th, so execute the r command after the execution of the program stopped here.
(GDB) R
Sixth step: View the call stack
(GDB) bt//BT is an abbreviation for BackTrace, which indicates backtracking tracking. #0表示当前栈帧, #1表示当前栈帧的上一个栈帧, and so on.
(GDB) p A/b is the abbreviation for print to see the value of parameter A in the current stack frame.
(GDB) Up/Up command select previous stack frame
(GDB) p A//view the value of parameter A in the current stack frame
Other GDB common commands:
b function//+ + functions name, set breakpoint at the beginning of the function.
S//step, executes a statement and, if there is a function call, goes inside the function.
N//Next, executes a statement and, if there is a function call, takes it as a whole.
In fact, we can write a recursive program that compares the difference between a generic call (not itself) and its own recursive invocation, and you can see that in C, there is no essential difference between calling yourself and invoking other functions, creating a new stack frame, passing parameters and modifying the "Current line of Code" (Control transfer). Delete the stack frame after the function body has finished executing, process the return value and modify the current line of code.
The >size a.exe command allows you to see the size of each segment in the executable file. An executable consists of the text (body segment, stored instruction), data (segment, stored initialized global variable), and BBS segment (which stores uninitialized global variables). In the run-time call stack is created, it is located in a stack segment, like other segments, has its own size, cannot cross-border access, otherwise there will be a segment error, that is, the so-called stack overflow, because the stack segment size is fixed, so recursive calls too much or too many local variables can cause the stack overflow, So we often define large arrays as global variables.
Reference: "Algorithmic Competition Primer Classic"--Rujia
GdB Debugger Common commands