On Sun, 18 Jun 2006 19:56:45 GMT, Keith Thompson <ks***@mib.org>
wrote:
Bit byte <fl**@flop.com> writes:
I am providing this C interface into another language, where there is
a great possibility of misuse and integers may be passed
(accidentally) to my functions, which use this validation macro
above. I want my library to be robust in the presence of such errors -
in otherwords, I need to be able to handle memory (READ) access
violations gracefully and to be able to recover from them - it is
fairly trivial to do this in C++, but I can't seem to find a way to do
this in C.
There's no way in C to test whether a pointer is valid. You can
easily test whether a pointer is null, but if it's non-null garbage,
any attempt even to look at its value invokes undefined behavior.
Not in standard C, the topic here. However, the conversion from
pointer types to (suitable) integers is nonnormatively "intended to
be consistent with the addressing structure of the execution
environment" and on all or nearly so platforms even indeterminate or
dangling pointers do give _some_ value which can usefully be analyzed
but only in a platform-dependent way.
<OT>I'm surprised that C++ provides a way to detect this; I would have
thought it also says this is undefined behavior.</OT>
Standard C++ does not. It does however provide syntax and mechanism
for exceptions, and _some_ implementations which are able to catch
invalid memory accesses, or other 'hardware' faults like zerodivide,
choose to have them raise platform-defined exceptions -- which can
then be handled using basically standard constructs.
_On these platforms_ using (standard C) signal() to establish a
handler for SIGSEGV or similar is very likely to work as well.
As already noted this is only a half-measure; on almost all systems it
is trivial to construct, and often easy to get by accident, pointer
values which don't cause an immediate fault but are nonetheless
invalid and when used cause horribly bad results. (I once had a really
bad Heisenbug of this type; if the program was run under the debugger
the invalid pointer it used happened to be benign, but if run without
the debugger it got a different invalid pointer which caused a crash.)
- David.Thompson1 at worldnet.att.net