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?
C++: Checking for a deleted pointer
Is there a way to check to see if the memory a pointer points at has been deleted?
e.g.:
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.
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.
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
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.
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement