用gdb调试程序(Linux环境)
一般来说,GDB主要帮忙你完成下面四个方面的功能:
1、启动你的程序,可以按照你的自定义的要求随心所欲的运行程序。
2、可让被调试的程序在你所指定的调置的断点处停住。(断点可以是条件表达式)
3、当程序被停住时,可以检查此时你的程序中所发生的事。
4、动态的改变你程序的执行环境。
GDB can do four main kinds of things (plus other things in support of these) to help you catch bugs in the act:
(参考:Debugging with GDB https://sourceware.org/gdb/current/onlinedocs/gdb/)
- Start your program, specifying anything that might affect its behavior.
- Make your program stop on specified conditions.
- Examine what has happened, when your program has stopped.
- Change things in your program, so you can experiment with correcting the effects of one bug and go on to learn about another.
一个调试示例:
1、源程序:tst.c
1 #include <stdio.h> 2 3 int func(int n) 4 { 5 int sum=0,i; 6 for(i=0; i<n; i++) 7 { 8 sum+=i; 9 } 10 return sum; 11 } 12 13 14 int main() 15 { 16 int i; 17 long result = 0; 18 for(i=1; i<=100; i++) 19 { 20 result += i; 21 } 22 23 printf("result[1-100] = %ld /n", result ); 24 printf("result[1-250] = %d /n", func(250) ); 25 }
2、 编译生成执行文件:#gcc -g tst.c -o tst
3、启用GDB调试程序
4、#gdb tst //启动gdb,进入gdb调试环境
5、(gdb)list //list命令 从第一行开始列出源码
8 sum+=i; 9 } 10 return sum; 11 } 12 13 14 int main() 15 { 16 int i; 17 long result = 0;
6、(gdb) //直接回车,表示执行上一条命令
18 for(i=1; i<=100; i++) 19 { 20 result += i; 21 } 22 23 printf("result[1-100] = %ld /n", result ); 24 printf("result[1-250] = %d /n", func(250) ); 25 }
7、(gdb) //直接回车,表示执行上一条命令
Line number 26 out of range; tst.c has 25 lines.
8、(gdb) break 16 //在源程序tst.c第16行设置断点
Breakpoint 1 at 0x400563: file tst.c, line 16.
9、(gdb)break func //在源程序中函数func()的入口处设置断点,断点在第5行
Breakpoint 2 at 0x400534: file tst.c, line 5.
10、(gdb)info break //查看断点信息
Num Type Disp Enb Address What 1 breakpoint keep y 0x0000000000400563 in main at tst.c:16 2 breakpoint keep y 0x0000000000400534 in func at tst.c:5
11、(gdb)r //输入r,r是run命令的简写
Starting program: /root/c_study/tst Breakpoint 1, main () at tst.c:17 17 long result = 0; Missing separate debuginfos, use: debuginfo-install glibc-2.17-196.el7_4.2.x86_64
12、(gdb)n //输入n,n是next命令的简写,next命令:执行下一条程序
18 for(i=1; i<=100; i++)
13、(gdb)n
20 result += i;
14、(gdb)n
18 for(i=1; i<=100; i++)
15、(gdb)n
20 result += i;