c++ - 为什么未处理的异常会导致段错误?

标签 c++ exception segmentation-fault

这是一个最小的例子:

[joel@maison various] (master *)$ cat throw.cpp 

#include <iostream>


int main(int argc, char* argv[])
{
  throw("pouet pouet");
}

[joel@maison various] (master *)$ ./a.out 
terminate called after throwing an instance of 'char const*'
Aborted (core dumped)

阅读文档,似乎默认的终止处理程序是 abort()。我在中止手册页中找不到任何关于触发段错误的内容。

最佳答案

抛出异常而不处理它会调用 abort(),这会引发 SIGABRT

您可以通过以下方式验证

#include <iostream>
#include <stdexcept>
#include <signal.h>

extern "C" void handle_sigabrt(int)
{
    std::cout << "Handling and then returning (exiting)" << std::endl;
}

int main()
{
  signal(SIGABRT, &handle_sigabrt);

  throw("pouet pouet");
}

Demo

关于c++ - 为什么未处理的异常会导致段错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41765875/

相关文章:

C++ 和结构(多重继承)

c++ - 为什么这个 boost 变换操作会把第二个元素弄错?

exception - 抛出额外的异常以避免代码重复

c# - WPF 全局异常处理程序

c++ - CMake 在 Windows 10 下使用 GTest - fatal error LNK1104 : cannot open file 'gtest.lib' , 但存在调试 'gtestd.lib'

c++ - 如何在字符串中添加换行符?

python - 内置 Numpy 异常?

c - 为什么 argc 与 strlen(argv[i]) 不同?

php - 来自 php 执行 c 脚本的错误消息

c++ - 段错误(C++)