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