打印分段故障原因

前端之家收集整理的这篇文章主要介绍了打印分段故障原因前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
参见英文答案 > How to generate a stacktrace when my gcc C++ app crashes28
假设我有一个导致分段错误代码.
char * ptr = NULL;
*ptr = "hello"; /* this will cause a segmentation fault */

如何在运行时打印分区故障发生的内存中的地址,以及分段故障的原因(访问禁止的内存区域或其他内容).

我读了关于核心转储文件,但我不知道这是否是正确的解决方案.

我该怎么做?

我知道我可以通过使用gdb或其他调试器来实现这一点,但目的是通过使用代码来实现,只有代码.

解决方法

如果你想知道原因,你可以注册一个信号处理程序,像:
void handler(int signum,siginfo_t *info,void *context)
{
  struct sigaction action = {
    .sa_handler = SIG_DFL,.sa_sigaction = NULL,.sa_mask = 0,.sa_flags = 0,.sa_restorer = NULL
  };

  fprintf(stderr,"Fault address: %p\n",info->si_addr);
  switch (info->si_code) {
  case SEGV_MAPERR:
    fprintf(stderr,"Address not mapped.\n");
    break;

  case SEGV_ACCERR:
    fprintf(stderr,"Access to this address is not allowed.\n");
    break;

  default:
    fprintf(stderr,"Unknown reason.\n");
    break;
  }

  /* unregister and let the default action occur */
  sigaction(SIGSEGV,&action,NULL);
}

然后你需要注册的地方:

struct sigaction action = {
    .sa_handler = NULL,.sa_sigaction = handler,.sa_flags = SA_SIGINFO,.sa_restorer = NULL
  };


  if (sigaction(SIGSEGV,NULL) < 0) {
    perror("sigaction");
  }

基本上,您注册SIGSEGV交付时触发的信号,并获得一些其他信息,以引用手册页:

06002

这些映射到获取分段错误的两个基本原因 – 您访问的页面根本没有映射,或者您不能执行您尝试该页面的任何操作.

在信号处理程序触发之后,它会自动注销并替换默认操作.这导致无法再次执行的操作,因此可以被正常路由捕获.这是页面错误的正常行为(获得seg故障的前身),以便像需求寻呼一样工作.

原文链接:https://www.f2er.com/c/115207.html

猜你在找的C&C++相关文章