用C捕获段错误 [英] Catching segfaults in C

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

问题描述

我有一个从指针运算有时会出现segfaults的程序。我知道这会发生,但我不能很容易地检查时间提前看它是否出现segfaults与否 - 无论是我能pre-扫描输入数据,看它是否会导致段错误(可以是不可能的确定),或者我可以改装它不使用指针运算,这需要工作的一个显著金额较大,或者我可以尝试赶上一个段错误。所以我的问题:

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)如何在C,可我抓住段错误?我知道的的东西的操作系统中引起段错误,但是可以在C程序中,它出现segfaults以更为优美死一点不仅仅是分割故障时做

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)如何便携式是什么?

2) How portable is this?

我想这是一个非常不可移植的行为,因此,如果您张贴任何code搭上段错误,请告诉我这是什么工程上。我在Mac OS X,但我想我的程序,以尽可能多的平台上工作,因为它可以,我想看看我的选择。

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.

和不要担心 - 基本上所有我想要做的就是打印更加用户友好的错误消息,并释放一些的malloc() ED内存,然后死亡。我不打算只是忽略所有的设计缺陷,我得到耕翻和未来。

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.

推荐答案

您必须定义一个信号处理程序。这是使用功能 的sigaction 。我做这个用在Fedora 64位和32位在同一code和Sun Solaris上。

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

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