1. What is GDB?
GDB : GNU Debugger is a debugger developed by the GNU Project for the GNU operating system, but its use is not limited to the GNU operating system. GDB can run on UNIX, Linux and even Microsoft Windows. You can debug programs written in C, C++, Objective-C, Pascal, Ada and other languages.
Use of GDB:
- Set a breakpoint to stop the program
- Monitor or modify the value of variables in the program
- Track code execution
Note : When compiling the program with gcc, you need to add the -g option (add debugging information to the program); such as:
gcc -o test -g test.c
2. How to debug with GDB
Sample code ( gdb.c ):
#include <stdio.h>
void ShowRevertNum(int iNum)
{
while (iNum > 10)
{
printf("%d", iNum % 10);
iNum = iNum / 10;
}
printf("%d\n", iNum);
}
int main(void)
{
int iNum;
printf("Please input a number :");
scanf("%d", &iNum);
printf("After revert : ");
ShowRevertNum(iNum);
}
Program description : Realize the inversion function of an integer number, such as input 1234 and return 4321.
But when inputting 100, it returns 010, I believe you have found the problem
So now we use the gdb tool to debug
gcc -o testgdb -g gdb.c
gdb testgdb
a.
Familiar with gdb commands
command | Description |
---|---|
l | Show code lines |
b(break) | Set breakpoint |
run | execute program |
whatis | Variable data type view |
c | Continue execution |
s | Single step debugging |
n | Single step |
quit | Terminate gdb debugging |
View the value of a variable |
b.
Debug with gdb , track the running track of the program when the input sample is 100
Through debugging, it is found that when iNum=10, iNum>10 is false, so the program directly jumps out of the loop and outputs iNum, which is 10; therefore, the final output result is 010.
c.
Modify the code
Through gdb debugging, I found the problem, that is, when iNum=10, the program will jump out of the loop. To prevent the program from jumping out at this time, just change " while (iNum> 10) " to " while (iNum >= 10) "
Recompile and run the program: