c++ - 在 C++ 中多次处理段错误

标签 c++ segmentation-fault

我能够处理一次段错误。但是当它再次发生时会导致段错误。是否可以多次处理 sigsegv 信号?

#define _POSIX_SOURCE
#include <signal.h>
#include <stdio.h>

int *a;

class FoobarException
{
  int thingy;
};

void signal_handler(int signum, siginfo_t *info, void *)
{
  printf("signal_handler\n");
  FoobarException *f = new FoobarException;
  throw f;
}

void call(int * c)
{
  struct sigaction act;
  act.sa_sigaction = signal_handler;
  sigemptyset (&act.sa_mask);
  act.sa_flags = SA_SIGINFO;
  sigaction (11, &act, NULL);

  try
    {
      printf("%d\n", *a);
    }
  catch (FoobarException *f)
    {
      printf("Hello!\n");
    }
}

int main()
{ 
  int *b;
  call(b);
  printf("I am here.\n");
  call(a);
}

第一个 call(b) 处理段错误,但第二个 call(a) 引发段错误。

最佳答案

一旦您遇到段错误,并且您处理了异常,但您没有恢复原因。打赌是为了避免段错误。在你的示例程序中,你有指针,ab 但没有分配,所以,ab包含垃圾(未分配),因此访问 *a 是有风险的,会导致段错误。

相反,为ab分配足够的空间,例如,

a = (int *) malloc(sizeof (int));

同样,对于b

不要忘记在完成后释放,比如,

free(a);

关于c++ - 在 C++ 中多次处理段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25887200/

相关文章:

c - 为什么节点没有正确添加以及为什么它打印相反? (单链表)

c - 传递指针和分配内存导致段错误

c++ - 使用 qsort 导致段错误

c - 当我接受矩阵的第一个值时出现段错误

c++ - 像打包一样获取聚合的大小

c++ - 宏的 if 语句中的变量初始化

c++ - 重载 << C++

c++ - QLineEdit 与 QValidator : React to editing finished regardless of input validity?

c++ - 如何使用 std::tuple 中的值作为函数参数?

c++ - 指针段错误问题