如何在C&C ++中查找细分错误?(使用GDB)
分段错误是运行时错误之一,它是由于内存访问冲突引起的,例如访问无效的数组索引,指向一些受限地址等。在本文中,我们将看到如何使用GDB工具检测这种类型的错误。。
让我们看一下代码和找到错误的相应步骤。
示例
#include <stdio.h>
main() {
int* ptr = NULL;
*ptr = 1; //trying to access unknown memory location
printf("%p\n", ptr);
}使用“gcc–gprogram_name.c”编译代码,然后使用“./a.out”运行
输出结果
soumyadeep@soumyadeep-VirtualBox:~/Cpp_progs$ ./a.out Segmentation fault (core dumped)
发生细分错误。
写'gdb./a.outcore'
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: <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 ./a.out...done. /home/soumyadeep/Cpp_progs/core: No such file or directory. (gdb)
输入“r”,然后按Enter。
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
热门推荐
1 训练狗狗搜寻
2 如何训练狗狗装死
3 狗狗训练书
6 怎么训练狗狗拜年
8 狗狗训练游戏
10 狗狗嗅觉训练
11 怎么训练狗狗在笼子里不叫
12 怎么训练狗狗站立走路
13 怎么训练狗狗在马桶上
14 狗狗尿尿怎么训练
15 训练狗狗用品
16 泰迪狗狗的训练方法大小便
17 训练狗狗可以打吗
18 王曼丽的狗狗训练