在C中捕捉segfaults [英] Catching segfaults in C

查看:148
本文介绍了在C中捕捉segfaults的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个程序有时会从指针运算中发生故障。我知道这种情况发生了,但是我不能很容易地提前检查它是否存在segfaults - 我可以预扫描输入数据,看看是否会导致segfault(这是不可能确定的)或者我可以重新指定它不使用指针算术,这将需要大量的工作量,或者我可以尝试抓住一个segfault。所以我的问题:



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屋!

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