sinbad said:
finding the validity of the address pointed to by a pointer,
how this can be done.
a pointer "ptr" having a value of 0x808 is obviosuly not a
valid value. At the same time a value of 0xffffffff or 0x0000000
is inavalid and if a process address space is inbetween x and y;
any pointer value "< x" or "> y" would be invalid.
Is it possible to write this kind of checking in c
under linux platform.
This isn't really a good question for comp.lang.c, since it doesn't have
much to do with the C language per se, it's really about Linux.
Crossposted and followups set to comp.os.linux.devel.applications
I think before answering this question, you should think about what you
mean by "valid", and why you want to know whether a pointer is "valid"
or not. What are you going to do with this information?
Other people have mentioned using /proc/self/maps to see if the pointer
points into a region of memory that the process has mapped. Certainly a
pointer that's not in one of these regions isn't very valid, since it
can't point to any object in your program and will cause a segfault if
dereferenced. But even if it is in one of these regions, there's other
reasons it might be pointing to the "wrong" place. Maybe you expect it
to point to an integer containing a number of lines, but it actually
points to the string "Hello world".
Also, regarding /proc/self/maps, doing this check is not very useful,
because what will you do if it fails? Abort the program? If you just
use the pointer, a segfault will do this for you. Clean up first, or
longjmp to some other part of the program? Then put this code in a
SIGSEGV handler. You're really just duplicating a check that the
hardware is already doing.
Sometimes people ask questions like this because they have a function
which takes a pointer as an argument, and, wanting to be careful
defensive programmers, they want to verify the pointer somehow before
they use it. Verifying that arguments make sense is generally a good
idea, but in the case of pointers it isn't really possible. The
function just doesn't know enough about the rest of the program to be
able to check that the calling function is doing what it wants to. In
this case you have to trust the caller. Just use the pointer. If it is
wrong, you'll find out when the program breaks, and that's when you turn
to your debugger to figure out what's going on in the rest of the
program.