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

时间:2017-01-20 14:25:32

标签: 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()。我无法找到关于在中止手册页中触发段错误的任何内容。

1 个答案:

答案 0 :(得分:6)

抛出异常而不处理异常会调用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