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调试工具的一小部分,希望起到作用。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值