【gdb】讨厌的段错误 how to debug "Segment Fault" on Linux

本文详细介绍了使用GDB调试工具定位Seg Fault错误的方法,包括添加断言检查内存访问对齐、使用gdb查找错误发生的具体代码行等步骤。

Overview

We can get SegFault by several reasons:

  • aligned access to unaligned memory(usally see in ARM NEON)
  • cross-border access

    int temp[2] = {0};
    temp[2] = 2; // SegFault
  • write on read-only access

    char *temp = "Haha";
    temp[1] = 2; // SegFault
  • others

How to find which code line results in segfault

Step 1: DEBUG

DEBUG flavour usually add some assert() statements about the memory alignment access.

Step 2: using gdb

If DEBUG flavour did not give any assert report, or you have fixed all the assert() report, but it still aborts with SegFault. What's next?

Usually, we can add "-g" compiler flag and rebuild the executable, then use gdb to locate where is the SegFault.

 1 /* main.c */
 2 #include <stdio.h>
 3 #include <stdlib.h>
 4 extern int f0();
 5 extern int f2();
 6 extern int f4();
 7 int f1();
 8 int f3();
 9 int main()
10 {
11     printf("Test for SegFault.\n");
12     return f4();
13 }
14 int f1()
15 {
16     return f0();
17 }
18 int f3()
19 {
20     return f2();
21 }
22  
23 /* segfault.c */
24 #include <stdio.h>
25 char f0()
26 {
27     char *tmp = "Haha";
28     tmp[0] = 'h';
29     return tmp[4];
30 }
31 char f2()
32 {
33     return f1();
34 }
35 char f4()
36 {
37     return f3();
38 }
example code

 build and run on terminal:

$ gcc main.c segfault.c -o segfault.x
$ ./segfault.x
Test for SegFault.
Segmentation fault (core dumped)
 

then with gdb:

$ gcc -g -O3 main.c segfault.c -o segfault.x
$ gdb ./segfault.x
GNU gdb (Ubuntu 7.7-0ubuntu3.1) 7.7
Copyright (C) 2014 Free Software Foundation, Inc.
(gdb) r
Starting program: /home/jxion/jxion_porting_server/users_jxion/test_segfault/segfault.x
Test for SegFault.
Program received signal SIGSEGV, Segmentation fault.
f0 () at segfault.c:6
6           tmp[0] = 'h';
(gdb) bt
#0  f0 () at segfault.c:6
#1  0x0000000000400557 in f1 () at main.c:19
#2  0x000000000040058b in f2 () at segfault.c:12
#3  0x0000000000400567 in f3 () at main.c:24
#4  0x000000000040059b in f4 () at segfault.c:17
#5  0x00007ffff7a35ec5 in __libc_start_main (main=0x400440 <main>, argc=1, argv=0x7fffffffd6f8, init=<optimized out>, fini=<optimized out>, rtld_fini=<optimized out>, stack_end=0x7fffffffd6e8)
    at libc-start.c:287
#6  0x0000000000400482 in _start ()
(gdb)
 

Now you can get all info you need.

转载于:https://www.cnblogs.com/xjsxjtu/p/3958390.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值