红联Linux门户
Linux帮助

利用gdb定位段错误(Segmentation fault)

发布时间:2016-03-06 09:56:21来源:linux网站作者:小威威__

用linux编程时,我们不时会遇到Segmentation fault,其实这就是段错误。引发段错误通常是数组越界,出现野指针,在一些作业网上可能也会显示runtime error,遇到这种情况我们该怎么办?难道一行一行看代码?

显然要调试程序。这里我用的是gdb。


apple@ubuntu:~/Desktop$ gdb
GNU gdb (Ubuntu 7.9-1ubuntu1) 7.9
Copyright (C) 2015 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".
(gdb) file a.out
Reading symbols from a.out...done.
(gdb) run
Starting program: /home/apple/Desktop/a.out
2
648 822 
7

Program received signal SIGSEGV, Segmentation fault.
0x00000000004007ec in pop (top=0x7fffffffdf10) at stack.h:27
27      if (p1->next == NULL || p1 == NULL) {
(gdb) p p1->next
Cannot access memory at address 0x8
(gdb) p p1
$1 = (Node *) 0x0
(gdb) quit
A debugging session is active.
Inferior 1 [process 11453] will be killed.
Quit anyway? (y or n) y


调用gdb后输入 file a.out,然后再输入run,就能发现段错误所在位置,然后通过“p 变量”指令,查询所在位置变量的值的情况。然后根据情况判断是哪个部分导致了段错误。


本文永久更新地址:http://www.linuxdiyf.com/linux/18657.html