您的位置:首页 > 其它

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

2015-12-30 22:04 866 查看

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

标签:gdb调试 段错误 定位

by 小威威

用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 变量”指令,查询所在位置变量的值的情况。然后根据情况判断是哪个部分导致了段错误。

以上内容皆为本人观点,欢迎大家提出批评和指导,我们一起探讨!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: