堆栈溢出时出现段错误 [英] Segfault on stack overflow

查看:241
本文介绍了堆栈溢出时出现段错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么Linux内核在堆栈溢出时生成segfault?当c或alltran中的临时数组创建溢出时,这会使调试变得很尴尬.当然,运行时很有可能会产生一个更有用的错误.

Why does the linux kernel generate a segfault on stack overflow? This can make debugging very awkward when alloca in c or fortran creation of temporary arrays overflows. Surely it mjust be possible for the runtime to produce a more helpful error.

推荐答案

您实际上可以使用信号处理程序来捕获堆栈溢出的条件.

You can actually catch the condition for a stack overflow using signal handlers.

为此,您必须做两件事:

To do this, you must do two things:

  • 使用sigaction为SIGSEGV(segfault)设置信号处理程序,为此设置SO_ONSTACK标志.这指示内核在传递信号时使用备用堆栈.

  • Setup a signal handler for SIGSEGV (the segfault) using sigaction, to do this set the SO_ONSTACK flag. This instructs the kernel to use an alternative stack when delivering the signal.

调用sigaltstack()设置SIGSEGV的处理程序将使用的备用堆栈.

Call sigaltstack() to setup the alternate stack that the handler for SIGSEGV will use.

然后,当堆栈溢出时,内核将在传递信号之前切换到备用堆栈.进入信号处理程序后,您可以检查导致错误的地址,并确定是堆栈溢出还是常规错误.

Then when you overflow the stack, the kernel will switch to your alternate stack before delivering the signal. Once in your signal handler, you can examine the address that caused the fault and determine if it was a stack overflow, or a regular fault.

这篇关于堆栈溢出时出现段错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆