C++文档阅读笔记-How to find Segmentation Error in C & C++ ? (Using GDB)

Posted IT1995

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了C++文档阅读笔记-How to find Segmentation Error in C & C++ ? (Using GDB)相关的知识,希望对你有一定的参考价值。

Segmentation Error:是在运行时对内存非法访问时报的错,比如非法读取内存。

这种报错在C/C++程序中很常见。

在下面这个例子中展示了如何在程序中找段错误,找到这个段错误是在程序代码的哪一行。

注意:这里使用的是Linux的Ubuntu操作系统演示。

首先编写如下代码:

// Segmentation Error Demonstration
// Author - Rohan Prasad
#include <iostream>
using namespace std;
  
int main()

    int* p = NULL;
  
    // This lines cause the segmentation 
    // error because of accessing the 
    // unknown memory location.
    *p = 1;
   
    cout << *p;
    return 0;

如何使用GDB找到错误源

将上面的这个文件保存为Program1.cpp。打开终端,进入Program1.cpp所在目录

①编译

$ gcc -g Program1.cpp (in my case).

②运行

$ ./a.out (it is Object File)

这里会报出错,异常原因是段错误

Segmentation fault (core dumped)

③使用gdb调试程序

$ 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
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:
.
Find the GDB manual and other documentation resources online at:
.
For help, type "help".
Type "apropos word" to search for commands related to "word"...
Reading symbols from ./a.out...done.
/home/logarithm/Desktop/Test Case/Miccl/core: No such file or directory.
(gdb)

这里键盘输入r,并且按下回车键

(gdb) r
Starting program: /home/logarithm/Desktop/Test Case/Miccl/a.out

Program received signal SIGSEGV, Segmentation fault.
0x00005555555547de in main () at Sege.cpp:8
8 *p=1;
(gdb)

现在就可以知道端错误在第8行*p = 1这个地方,这里输入quit就能退出了。

(gdb) quit
A debugging session is active.

Inferior 1 [process 3617] will be killed.

Quit anyway? (y or n) y

以上是关于C++文档阅读笔记-How to find Segmentation Error in C & C++ ? (Using GDB)的主要内容,如果未能解决你的问题,请参考以下文章

C++文档阅读笔记-How to find Segmentation Error in C & C++ ? (Using GDB)

C++文档阅读笔记-How to find Segmentation Error in C & C++ ? (Using GDB)

C++文档阅读笔记-Smart Pointers in C++ and How to Use Them

C++文档阅读笔记-Smart Pointers in C++ and How to Use Them

C++文档阅读笔记-Smart Pointers in C++ and How to Use Them

Laravel文档阅读笔记-How to use @auth and @guest directives in Laravel