Reputation: 1701
A dirty hack to determine whether a pointer (of any type) is mapped to the current process is to pass the pointer to the access
system call, then check errno
for EFAULT
. Another is to use munlock
and check for ENOMEM
. Another is to parse /proc/PID/maps
. Is there a method with fewer side-effects, preferably without depending on procfs?
Upvotes: 1
Views: 110
Reputation: 39847
A method to check your pointer for access is to simply try to use it; if you have no access you will receive a SIGSEGV -- which you can catch with your own signal handler.
To do this, you will want to use the setjmp()
function prior to accessing the pointer, and you will want your signal handler to longjmp()
out. Something along these lines:
if (setjmp(jmp_buf)) printf("The pointer was inaccessible.\n");
else {
int x = *ptr;
printf("The pointer was readable.\n");
}
In your signal handler, you'll want to:
...
longjmp(jmp_buf, 1);
This will cause your application to resume at a particular point within the setjmp()
function, in a manner that restores all registers and causes the function to return 1
(instead of its default of 0
).
Upvotes: 1