C++: Checking for a deleted pointer

Started by
8 comments, last by Eyrian 17 years, 9 months ago
Is there a way to check to see if the memory a pointer points at has been deleted? e.g.:

int* a = new int(5);
int* b = a;

delete a;

(*b)++; // Causes crash!
Is there any way to make a check around the dereference to see if it should not be performed?
Advertisement
Not in standard C++. Consider using smart pointers instead.
No. C++ is agnostic as far as the state of memory at the end of a pointer goes.

You may decide to implement your own allocator to handle such cases, though. A hashtable or map of spans could work.
boost::shared_ptr< int > a( new int(5) );boost::weak_ptr< int > b( a );a.reset();boost::shared_ptr< int > b_shared = b.lock();if ( b_shared ) {    (*b_shared)++;} else {    //deleted}


Not exactly equivilant to what you posted for various reasons, but it's a small inkling into the power of the [boost] smart_ptr library.
You could always set the pointer to NULL after you delete it, and then check it before you access it.
Ra
Quote:Original post by Ra
You could always set the pointer to NULL after you delete it, and then check it before you access it.


Take another look at his example. Nulling a out won't help for b.
Quote:Original post by Ra
You could always set the pointer to NULL after you delete it, and then check it before you access it.


Even if a is nulled, b is not.

EDIT: feh, 20 seconds late. I blame my laggy WiFi.
for this sample, a workaround:
int* a = new int(5);
int*& b = a;
delete a;
(*b)++; // Ok

not really useful in "real" world ineed
Quote:Original post by peous
for this sample, a workaround:
int* a = new int(5);
int*& b = a;
delete a;
(*b)++; // Ok


Erm, no, that won't work.

If you null out a in that example after deletion, and use:

if (b) (*b)++;

Then it would work for this highly constrained example.
Unfortunately, using a reference isn't really compatible with what I'm doing. Nor are smart pointers. It seems that an allocation/deletion map is the only way to go.

Thanks for the replies, all.

This topic is closed to new replies.

Advertisement