在C中捕捉segfaults [英] Catching segfaults in C
问题描述
1)如何在C中,我能抓住一个segfault吗?我知道操作系统中的某些东西会导致一个segfault,但是如果一个C程序在某些情况下可以更精确地死亡,而不仅仅是分段错误
?
2)这是多么便利?
我想象这是一个非常不可取的行为,所以如果你发布任何代码来捕捉segfault,请告诉我它的作用。我在Mac OS X上,但我希望我的程序可以在尽可能多的平台上工作,我想看看我的选择。
不用担心 - 基本上我所要做的就是打印一个更加人性化的错误信息,并释放一些 malloc()
ed内存,然后死机。我不打算只是忽略我所获得的所有segfaults和向前推进。
你必须定义一个信号处理程序。这在Unix系统上使用 sigaction
。我在Fedora 64位和32位以及Sun Solaris上使用了相同的代码。
I have a program that segfaults from pointer arithmetic sometimes. I know this happens, but I can't easily check ahead of time to see whether it segfaults or not - either I can "pre-scan" input data to see if it will cause a segfault (which can be impossible to determine), or I can refit it to not use pointer arithmetic, which would require a significantly larger amount of work, or I can try to catch a segfault. So my question:
1) How, in C, can I catch a segfault? I know something in the OS causes a segfault, but what can a C program do in the event that it segfaults to die a bit more gracefully than just Segmentation fault
?
2) How portable is this?
I imagine this is a highly unportable behavior, so if you post any code to catch a segfault, please tell me what it works on. I'm on Mac OS X but I'd like my program to work on as many platforms as it can and I want to see what my options are.
And don't worry - basically all I want to do is print a more user-friendly error message and free some malloc()
ed memory, and then die. I'm not planning on just ignoring all segfaults I get and plowing ahead.
You have to define a signal handler. This is done on Unix systems using the function sigaction
. I've done this with the same code on Fedora 64- and 32-bit, and on Sun Solaris.
这篇关于在C中捕捉segfaults的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!