2.调试器gdb
三大功能:启动被调试程序,
让被调试的程序在指定位置停住,
当程序停住时,可检查此时程序中所发生的事。
命令行
以demo.c为例
gcc -g demo.c -o demo |
调试 |
gdb demo |
进入调试 |
run |
执行可执行文件 |
list |
查看代码* |
break 20 |
在20行打断点 |
break 20 if i=10 |
在i=10时在20行停住 |
break +函数名 |
在调用此函数时暂停 |
printf i |
查看当前的i值 |
info break |
查看断点信息 |
delete 1 |
删除断点信息(数字代表断电编号) |
next |
单步执行,但不可进入子程序 |
step |
单步执行,可以进入子程序 |
finish |
继续执行,结束当前函数,之后不再运行 |
continue |
继续当前断点之后的程序,执行到下一个断点或者执行到最后 |
quit |
推出gdb |
List
(gdb) list line1,line2
查看源代码
list lineNum 在lineNum的前后源代码显示出来
list + 列出当前行的后面代码行
list - 列出当前行的前面代码行
list function
set listsize count
设置显示代码的行数
show listsize
显示打印代码的行数
list first,last
显示从first到last的源代码行
对段错误进行调试
run之后停在哪一行,就是哪一行出现了段错误
如下所示函数
02.c
1 #include <stdio.h>
2 #include"debug.h"
3 int main()
4 {
5 debug_msg("a!\n");
6 char *ptr="hello word";
7 debug_msg("b!\n");
8 ptr++;
9 debug_msg("c!\n");
10 printf("ptr=%s\n",ptr);
11 debug_msg("D\n");
12 *ptr='L';
13
14 return 0;
15 }
debug.h
1 #define __DEBUG__
2 #ifndef __DEBUG__
3 #define debug_msg(fmt, args...)
4 #else
5 #define debug_msg(fmt, args...) printf(fmt, ##args)
6 #endif
[root@promote 0708]# gcc 02.c
[root@promote 0708]# ./a.out
a!
b!
c!
ptr=ello word
D
段错误
所以D之后出现错误,12行出错。
也可以删除debug.h的第一行
[root@promote 0708]# gcc 02.c
[root@promote 0708]# ./a.out
ptr=ello word
段错误
看不出来哪里出现错误
执行以下步骤
[root@promote 0708]# gcc 02.c -D__DEBUG__
[root@promote 0708]# ./a.out
a!
b!
c!
ptr=ello word
D
段错误
-D是指加上头文件