How can I prevent (not respond) to a segmentation error?

I am not trying to handle the segmentation error. I understand how exception handling works, more or less. I would rather not make a mistake first. What I want to do is call a function or perform an operation that returns a value telling me whether a specific location / memory block is available or not, without actually accessing it and receiving an error.

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

result = probe_memory(address,length) 

where is the result

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

or something like that.

Is there anything similar on Linux and / or Mac OS X?

+1
c segmentation-fault linux macos
source share
3 answers

I believe something is more or less like the following:

 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 the protection of the page.

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

Jonathan Leffler wrote a fully-processed implementation in his repository of stack repositories .

+3
source share

You can use mincore (2) , and you can read sequentially and parse /proc/self/maps , see Proc (5) .

Please note that Linux is not designed to quickly obtain this mapping information. It is well known that swapping emulation of applications (for example, external GNU / Hurd pagers ...) is slow. (for example, using some low-level handler, SIGSEGV handler).

If your only goal is to provide feedback on SIGSEGV , you can use Ian Taylor libbacktrace from the GCC source code.

As said in some comments, maybe you want valgrind .

+1
source share

You forgot in your answer list - a writable, but used OS / something critical / actually self-tuning memory mapping, etc.

It’s best to try to make the code skipped code, of which you only write to the places where you own.

It will probably be faster, more reliable, portable, and more maintainable to isolate, verify, copy, modify, to try to twist the OS (s) arm to provide the necessary information, and much more than to try to verify it yourself.

0
source share

All Articles