ju**********@yahoo.co.in writes:
pi************@gmail.com wrote: When a function is given a pointer, it is tempting to do an assert on
the pointer to see if it is not NULL. But even if it is not NULL, it
could still be invalid or wrong. What we really want to know is that it
points to memory that we have access to. How about doing this:
void f(int* p)
{
assert(*((char*)p) == *((char*)p);
}
To see if pointer points to something that I have access to?
Is there another way of do something like this?
/David
If p is not a valid address, accessing it will cause exception.
<OT>
On a unix system, the kernel posts signal SIGSEGV to the application
indication when it accesses any invalid address. So, first insatll
a handler for SIGSEGV. Do a setjmp() before varifying the address
and then do a longjump from the signal handler.
In embedded systems, you may replace the exception handler with that
of yours that would pass some information to the application
whether the address was valid/invalid.
</OT>
As others have pointed out, there is no portable way to determine
whether a pointer is valid. There are a number of non-portable ways
to do this check (such has catching SIGSEGV) -- but that still leaves
the question of what to do once you've detected the error.
An invalid pointer almost certainly indicates a bug in your program.
Attempting to continue executing with a known bug could well cause
more damage. Very often, the best way to handle the bug is to let the
program die immediately, and let the operating system produce whatever
diagnostics it can. Then fix the bug, recompile, and try again -- or
submit a bug report and ask for your money back.
In some cases, you might want to do some cleanup before terminating
the program. For example, you might try to update and close any open
files to avoid losing too much information. This can still be
dangerous, though, if the bug can affect the cleanup code. It's often
better to write the program so it's always in a consistent state (for
example, any file are periodically updated); this will also handle
things like turning off the power while the program is running.
In some (but not all) safety-critical applications, shutting down the
program might be the worst thing you could do. For example, you might
have a choice between attempting to continue executing (perhaps in
some safe mode) and letting the airplane crash. In such cases, it
makes sense to use whatever system-specific means are available to
detect errors -- and then kick yourself for letting such an error get
into the production version of the program. (Many would question
whether C is an acceptable language for such an application.)
--
Keith Thompson (The_Other_Keith)
ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.