如何防止(不对)分段错误? [英] How can I prevent (not react to) a segmentation fault?

查看:20
本文介绍了如何防止(不对)分段错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不想处理分段错误.我或多或少地了解异常处理的工作原理.我宁愿一开始就没有错.我想要做的是调用一个函数或执行一个返回一个值的操作,该值告诉我该特定内存位置/块是否可访问,而无需实际访问它并得到错误.

也就是说,我想要一个 C 函数在实际访问它之前探测 Linux 和/或 Mac OS X 中的地址.比如:

result = probe_memory(address,length)

结果在哪里

 0 = 可写1 = 只读-1 = 不存在

或类似的东西.

在 Linux 和/或 Mac OS X 中有类似的东西吗?

解决方案

我相信或多或少像下面这样的东西应该可以工作:

int probe_memory(void *address, size_t length) {整数结果,fd[2];管道(FD);/* 记得检查错误!*/错误号 = 0;结果 = 写入(fd[1],地址,长度);if (result < 0 || (size_t)result != 长度 || errno == EFAULT) {结果 = 0;} 别的 {结果 = 1;}关闭(fd[0]);关闭(fd[1]);返回结果;}

<块引用>

这是您问题的部分解决方案,因为此代码不检查页面保护.

基本思路是让操作系统通过调用writeaddress中读取length字节.如果内存不可访问,它将返回 EFAULT 而不会触发段错误.

Jonathan Leffler 在他的 堆栈溢出问题存储库.

I am not trying to handle a segmentation fault. I understand how exception handling works, more or less. I would rather not have the fault in the first place. What I want to do is call a function or perform an operation that returns a value telling me whether or not that particular memory location/block is accessible, without actually accessing it and getting the fault.

That is, I would like a C function to probe an address in Linux and/or Mac OS X before actually accessing it. Something like:

result = probe_memory(address,length)

where result is

 0 = writable
 1 = read-only
-1 = nonexistent

or something along those lines.

Is there anything like that in Linux and/or Mac OS X?

解决方案

I believe something more or less like the following should work:

int probe_memory(void *address, size_t length) {
    int result, fd[2];

    pipe(fd);  /* Remember to check for errors! */

    errno = 0;
    result = write(fd[1], address, length);

    if (result < 0 || (size_t)result != length || errno == EFAULT) {
        result = 0;
    } else {
        result = 1;
    }

    close(fd[0]);
    close(fd[1]);

    return result;
}

This is a partial solution to your problem, as this code does not check for page protection.

The basic idea is to let the OS read length bytes from address through the call to write. If the memory is not accessible, it will return EFAULT without triggering a segfault.

Jonathan Leffler wrote a fully worked up implementation in his Stack Overflow Questions repository.

这篇关于如何防止(不对)分段错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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