Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
369 views
in Technique[技术] by (71.8m points)

c - How can I prevent (not react to) a segmentation fault?

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...