Linux下分析进程segment fault的方法

长时间不用,命令容易忘,记录一下,以备忘.

1. 程序在编译时,记得加 -g 选项,以生成带符号表的目标程序.

2. 执行:

sudo echo "core" /proc/sys/kernel/core_pattern //需要root权限.进程碰到段错误后,生成名为core的文件,并存放在进程同目录.

ulimit -c unlimited

3. 段错误发生后,执行:

gdb ./程序名 ./core

示例:

Queue is empty: TRUE
Queue is full: FALSE
Element number in Queue: 0
We are going to add 5 elements into queue:
enqueue ok: q->data[0]=The first element
enqueue ok: q->data[1]=2:aaaaaaaaaaaaaaaaaaaaaaaaaaaaa
enqueue ok: q->data[2]=3:The third element
enqueue ok: q->data[3]=4:Bejing Beijing
enqueue ok: q->data[4]=5:The fivth element
Queue is empty: FALSE
Queue is full: FALSE
Element number in Queue: 5
We are going to remove 2 elements from queue:
段错误 (核心已转储)

执行gdb ./Queue ./core

$ gdb ./Queue ./core 
GNU gdb (Ubuntu 7.11.1-0ubuntu1~16.5) 7.11.1
Copyright (C) 2016 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 "x86_64-linux-gnu".
Type "show configuration" for configuration details.
For bug reporting instructions, please see:
<http://www.gnu.org/software/gdb/bugs/>.
Find the GDB manual and other documentation resources online at:
<http://www.gnu.org/software/gdb/documentation/>.
For help, type "help".
Type "apropos word" to search for commands related to "word"...
Reading symbols from ./Queue...done.

warning: exec file is newer than core file.
[New LWP 5377]
Core was generated by `./Queue'.
Program terminated with signal SIGSEGV, Segmentation fault.
#0  strlen () at ../sysdeps/x86_64/strlen.S:106
106	../sysdeps/x86_64/strlen.S: 没有那个文件或目录.
strlen()出错,这种一般因为入参为空指针,顺着代码排查即可.

猜你喜欢

转载自blog.csdn.net/weixin_42263483/article/details/80868034