如何使用 GDB 查找 C 和 C++ 中的分段错误?


分段错误是运行时错误之一,该错误是由内存访问违例引起的,例如访问无效的数组索引、指向某些限制性地址等。在本文中,我们将看到如何使用 GDB 工具检测此类错误。

让我们看看代码和定位错误的相应步骤。

示例

#include <stdio.h>
main() {
   int* ptr = NULL;
   *ptr = 1; //trying to access unknown memory location
   printf("%p\n", ptr);
}

使用“gcc –g program_name.c”编译代码,并使用“./a.out”运行。

输出

soumyadeep@soumyadeep-VirtualBox:~/Cpp_progs$ ./a.out
Segmentation fault (core dumped)

发生分段错误。

编写“gdb ./a.out core”

soumyadeep@soumyadeep-VirtualBox:~/Cpp_progs$ gdb ./a.out core
GNU gdb (Ubuntu 8.1-0ubuntu3) 8.1.0.20180409-git
Copyright (C) 2018 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:
<https://gnu.ac.cn/software/gdb/bugs/>.
Find the GDB manual and other documentation resources online at:
<https://gnu.ac.cn/software/gdb/documentation/>.
For help, type "help".
Type "apropos word" to search for commands related to "word"...
Reading symbols from ./a.out...done.
/home/soumyadeep/Cpp_progs/core: No such file or directory.
(gdb)

键入“r”,然后按回车键。

Starting program: /home/soumyadeep/Cpp_progs/a.out

Program received signal SIGSEGV, Segmentation fault.
0x000055555555465e in main () at 1230.find_seg_error.c:5
5 *ptr = 1; //trying to access unknown memory location
(gdb)

因此,我们已成功获取错误,现在退出 GDB

(gdb) quit
A debugging session is active.

Inferior 1 [process 2794] will be killed.

Quit anyway? (y or n) y

更新日期: 2019 年 7 月 30 日

1K+ 浏览量

助力您的职业生涯

完成课程并获得认证

开始
广告