在 C 中捕获段错误 [英] Catching segfaults in C
问题描述
我有一个程序有时会从指针算术中出现段错误.我知道会发生这种情况,但我不能轻易地提前检查它是否存在段错误 - 我可以预扫描"输入数据以查看它是否会导致段错误(这可能无法确定),或者我可以修改它以不使用指针算术,这需要大量的工作,或者我可以尝试捕获段错误.所以我的问题:
1) 在 C 语言中,我如何捕获段错误?我知道操作系统中的某些东西会导致段错误,但是如果 C 程序在段错误中比 Segmentation fault
更优雅地死掉,那么它可以做什么呢?p>
2) 这有多便携?
我想这是一个非常不可移植的行为,所以如果您发布任何代码来捕获段错误,请告诉我它的工作原理.我在 Mac OS X 上,但我希望我的程序可以在尽可能多的平台上运行,我想看看我的选择是什么.
别担心 - 基本上我想做的就是打印一个更用户友好的错误消息并释放一些 malloc()
ed 内存,然后死掉.我不打算只是忽略我遇到的所有段错误并继续前进.
你必须定义一个信号处理程序.这是在 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 中捕获段错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!