Linux 小玩意 如何使用GDB 来快速定位程序中Segmentation fault

如何使用GDB 来快速定位程序中Segmentation fault

GDB 是一个非常强大的调试工具, 是我们编程调试必不可少的工具。下面就让我们来使用它来调试一个常见的NULL 指针操作导致的 segmentation fault . 然后来初步认识了解这个强大的工具.

1. 我们来编写一个简单的C文件.

1
2
3
4
5
6
7
8
#include <stdio.h>
int main(){
int *killer = NULL;
printf("We are going to trigger a SegmentFault \n");
*killer = 1; /* trigger by operating NULL pointer*/
printf("Never reach \n");
return(0);
}

2. 使用GCC 来编译这个C 文件.

1
# gcc -g segmentFault.c -o segmentFault

3. 好了, 编译完成, 让我们来执行这个程序.

1
2
3
# ./segmentFault
We are going to trigger a SegmentFault
Segmentation fault

4,有了材料,这会让我们来看看怎么用GDB 来快速定位错误.

4.1, 首先, 先通过命令将GDB 与我们的问题程序加载起来.

1
2
3
4
5
6
7
8
9
10
11
#  gdb ./segmentFault
GNU gdb (GDB) Red Hat Enterprise Linux7.6.1-94.el7
Copyright (C) 2013 Free SoftwareFoundation, Inc.
License GPLv3+: GNU GPL version 3 or later<http://gnu.org/licenses/gpl.html>
This is free software: you are free tochange and redistribute it.
There is NO WARRANTY, to the extentpermitted by law. Type "showcopying"
and "show warranty" for details.
This GDB was configured as"x86_64-redhat-linux-gnu".
For bug reporting instructions, please see:
<http://www.gnu.org/software/gdb/bugs/>...
Reading symbols from/root/segmentFault...done.

4.2, 执行”run” 命令, 这会程序就在GDB 中运行起来了.

1
2
3
4
5
6
7
(gdb) run
Starting program: /root/./segmentFault
We are going to trigger a SegmentFault
Program received signal SIGSEGV,Segmentation fault.
0x000000000040054b in main () atsegmentFault.c:5
5 *killer = 1 ; /* trigger byoperating NULL pointer*/
Missing separate debuginfos, use:debuginfo-install glibc-2.17-157.el7.x86_64

4.3, Segmentfault 出现了, 好办,这会只要用”bt”命令就能把出现问题的地方找出来,方便快捷.

1
2
(gdb) bt
#0 0x000000000040054b in main () atsegmentFault.c:5

4.4, 到此, 我们可以清楚的看出来问题出在程序的第5行.

1
2
3
4
5
6
7
8
9
10
11
(gdb) list
1 #include <stdio.h>
2 int main(){
3 int *killer = NULL;
4 printf("We are going totrigger a SegmentFault \n");
5 *killer = 1 ; /* trigger byoperating NULL pointer*/
6 printf("Never reach\n");
7 return(0);
8
9 }
(gdb)