views:

183

answers:

6

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.)

+14  A: 

No, there is not.

James McNellis
+5  A: 

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.

dcp
+2  A: 

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).

Cogwheel - Matthew Orlando
+3  A: 

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.

Eric Brown
And even then you wouldn't know if it pointed to what anybody thought it did.
David Thornley
Enh - you could check the size, and a few other things, but yeah, there's no type data there...
Eric Brown
+1  A: 

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.

Vagrant
A: 

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.

Greg Domjan
Doesn't work. In general no exceptions are thrown if the pointer is invalid.
Nemanja Trifunovic
C++ doesn't mandate any exceptions get thrown, all you get is undefined behavior. (Which on some platforms means crashing, or throwing an exception.)
GMan
It was used on a Windows XP or earlier system, but as you say undefined for general usage.
Greg Domjan