GNU gdb 应用实例

GNU gdb 应用实例

一、用一个简单的例子说明如何使用gdb调试程序:

[root@localhost ~]# vi hello.c

#include <stdio.h>

#include <stdlib.h>

#include <string.h>

#include <unistd.h>

 

int main()

{

char *p = (char *)malloc(20);

strcpy(p,"123");

pid_t pid = getpid();

printf("%d",pid);

pause();

 

return 0;

}

该程序的功能是获取当前进程号,并把该进程号输出。

在调试之前,首先要利用gcc编译器编译程序,命令如下:

[root@localhost ~]# gcc -g hello.c -o t

其中,-g参数表示在编译过程中,编译器加入一些用于gdb调试的信息,否则,无法进行gdb调试。

编译成功之后生成t的可执行文件,可以进入gdb调试界面:

1>shell中输入以下命令进入gdb调试界面

[root@localhost ~]# gdb

GNU gdb (GDB) Fedora (7.2-16.fc14)

Copyright (C) 2010 Free Software Foundation, Inc.

License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>

This is free software: you are free to change and redistribute it.

There is NO WARRANTY, to the extent permitted by law.  Type "show copying"

and "show warranty" for details.

This GDB was configured as "i686-redhat-linux-gnu".

For bug reporting instructions, please see:

<http://www.gnu.org/software/gdb/bugs/>.

(gdb) file t

Reading symbols from /root/t...done.

(gdb) 

2>先输入gdb命令,再输入file t命令进入调试界面

[root@localhost ~]# gdb t

GNU gdb (GDB) Fedora (7.2-16.fc14)

Copyright (C) 2010 Free Software Foundation, Inc.

License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>

This is free software: you are free to change and redistribute it.

There is NO WARRANTY, to the extent permitted by law.  Type "show copying"

and "show warranty" for details.

This GDB was configured as "i686-redhat-linux-gnu".

For bug reporting instructions, please see:

<http://www.gnu.org/software/gdb/bugs/>...

Reading symbols from /root/t...done.

(gdb) 

list命令可以

 

设置断点开始调试:

(gdb) break 8

Breakpoint 1 at 0x804848d: file hello.c, line 8.

(gdb) run

Starting program: /root/t 

 

Breakpoint 1, main () at hello.c:8

8 char *p = (char *)malloc(20);

Missing separate debuginfos, use: debuginfo-install glibc-2.12.90-17.i686

(gdb) print *p

$1 = 124 '|'

(gdb) print p

$2 = 0x97dff4 "|ݗ"

(gdb) next

9 strcpy(p,"123");

(gdb) next

10 pid_t pid = getpid();

(gdb) print pid

$3 = 134513915

(gdb) next

11 printf("%d",pid);

(gdb) print pid

$4 = 2982

(gdb) kill

Kill the program being debugged? (y or n) y

(gdb) quit

[root@localhost ~]# 


以上只是gdb调试工具的一小部分,希望起到作用。

发布了32 篇原创文章 · 获赞 4 · 访问量 3万+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章