首页 > 代码库 > [SegFault] 讨厌的段错误 how to debug "Segment Fault" on Linux
[SegFault] 讨厌的段错误 how to debug "Segment Fault" on Linux
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 }
build and run on terminal:
$ gcc main.c segfault.c -o segfault.x$ ./segfault.xTest for SegFault.Segmentation fault (core dumped)
then with gdb:
$ gcc -g -O3 main.c segfault.c -o segfault.x$ gdb ./segfault.xGNU gdb (Ubuntu 7.7-0ubuntu3.1) 7.7Copyright (C) 2014 Free Software Foundation, Inc.(gdb) rStarting program: /home/jxion/jxion_porting_server/users_jxion/test_segfault/segfault.xTest for SegFault.Program received signal SIGSEGV, Segmentation fault.f0 () at segfault.c:66 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.
[SegFault] 讨厌的段错误 how to debug "Segment Fault" on Linux
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。