gdb调试工具

 GDB是GNU的调试工具,它可以跟踪被调试的程序,进行设置断点、单步执行等操作。

主要用于程序的排错,方便找出程序错误所在处。

如写一个程序测试char类型所能表示整数。

创建一个moshou.c文件,写入:

#include <stdio.h>

#include<string.h>
int main()
{
char a[1000];
int i;
for(i=0;i<1000;i++)
{
a[i]=-1-i;
}
printf("%d\n",strlen(a));
return 0;

}

在终端输入:

[root@localhost C]# gcc moshou.c
[root@localhost C]# ./a.out
255

可以看出结果是255

在终端输入 gcc 文件名.c -o moshou -g

[root@localhost C]# gcc moshou.c -o moshou -g  (或者写成gcc -g moshou.c -o moshou)
[root@localhost C]# ls
11  33  55  a.out    case.sh  File   hello.c   if    jisuan.c  moshou.c  pash.sh  quyu.c   shell.sh  sizeof.c  strlen.c    switch
22  44  a1  Author:  const.c  hello  hello.sh  if.c  moshou    pash      quyu     scanf.c  sizeof    strlen    strlen.c.c  switch.c
[root@localhost C]# gdb  moshou(输入gdb空格文件名,这时候就进入调试模式了)

以下是在gdb下几个操作指令:

一list 

格式简写 l空格数字

表示输入你想显示的程序所对应的行数,就可以看到vim编辑器下的程序内容了。

如:

(gdb) list 1
1 #include <stdio.h>
2 #include<string.h>
3 int main()
4 {
5 char a[1000];
6 int i;
7 for(i=0;i<1000;i++)
8 {
9 a[i]=-1-i;
10 }
(gdb) list 13
8 {
9 a[i]=-1-i;
10 }
11 printf("%d\n",strlen(a));
12 return 0;
13 }
(gdb) 

二break用来设置断点

格式:break空格想设置断点的行号

如:

(gdb) break 10
Breakpoint 1 at 0x80483be: file moshou.c, line 10.

这时候用run指令试运行一下程序:

(gdb) run
Starting program: /root/C/moshou 无


Breakpoint 1, main () at moshou.c:11 (Breakpoint是断点的编号,这里因为第10行是“}”无意义所以直接跳到11行)
11 printf("%d\n",strlen(a));       (这里就运行到第10行)

若:想查看有那几个断点,在什么位置。可以输入

(gdb) info break
Num Type           Disp Enb Address    What
1   breakpoint     keep y   0x080483be in main at moshou.c:10
breakpoint already hit 1 time

若 想让程序继续运行可以输入 continue

(gdb) contine
Undefined command: "contine".  Try "help".
(gdb) continue
Continuing.
255
Program exited normally.

若想删除断点可以输入delete break 断点编号(也可以不输入编号全部删除)

若想知道程序在运行过程中变量的值可以输入:print空格变量名

(gdb) print i
$2 = 1000

注:这个指令可以配合断点使用。

三,逐步运行程序,可以使用step(s)或者next(n)这里配合断点使用

比如断点设置第一行:

(gdb) break 1
Breakpoint 6 at 0x8048384: file moshou.c, line 1.
(gdb) run
The program being debugged has been started already.
Start it from the beginning? (y or n) y
Starting program: /root/C/moshou 
Breakpoint 6, main () at moshou.c:4
4 {
(gdb) s
main () at moshou.c:7
7 for(i=0;i<1000;i++)
(gdb) s
9 a[i]=-1-i;
(gdb) s
7 for(i=0;i<1000;i++)
(gdb) n
9 a[i]=-1-i;
(gdb) n
7 for(i=0;i<1000;i++)
(gdb) 

注:step可进去被调用函数 N不可以进入调用函数

输入return从当前函数返回(只能在函数里使用)

四:输入quit(q)可以gdb模式

(gdb) q
The program is running.  Exit anyway? (y or n) y
[root@localhost C]# 

猜你喜欢

转载自blog.csdn.net/zhouzi2018/article/details/80318814