Possible Duplicate:
Testing pointers for validity (C/C++)
If I have a pointer, like char* foo
, is there any way to determine if foo
points to a valid location in memory? (So, foo
is not NULL
, and delete
has not yet been called on it.)
Possible Duplicate:
Testing pointers for validity (C/C++)
If I have a pointer, like char* foo
, is there any way to determine if foo
points to a valid location in memory? (So, foo
is not NULL
, and delete
has not yet been called on it.)
No. It's pretty much your responsibility to make sure you don't use dangling pointers.
However, one practice recommended by that link (I've seen some people use this, others hate it) is to immediately set the pointer to NULL
after you free/delete it.
You can't determine whether foo points to a valid location, but there are plenty of things you can do to ensure such is the case (especially RAII).
Not in any implementation-independent manner.
If one knew the implementation details of the heap manager, one could walk the heap blocks and verify that the pointer is a valid heap block.
But that would be slow and (extremely) implementation dependent; it most likely would not work across compiler versions, much less across different compilers on the same OS, and certainly not across different OSes.
It's far better to ensure that the pointer is either valid or NULL, using something like RAII or smart pointers.
If you could determine such a thing, that would mean there was extra bloat and overhead that would not be required 99.999% of the time and that runs counter to the principles of C++.
If you are worried about this sort of thing then use boost::shared_ptr.
This is not pretty, I wouldn't do it as I prefer to use smart pointers, but here is some older style code.
valid location
I saw an interesting definition of valid once. If you can access it - say by using it, then it's valid. You can catch the exception raised when accessing it fails, thus you can define that it is valid or not. Valid in this case meaning 'accessible' but not defining anything about type.
valid_ptr( void * validate ) {
try {
int foo = *(int *)validate;
return true;
}
catch(...){}
return false;
}
This garauntees the memory is currently readable by your app, it does not mean your type specific pointer is pointing at an object of that type.
Perhaps a newer version of this method would also use a dynamic_cast or such to verify the type aswell trying to use RTTI information.