Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I determine if a C++ object has been deallocated?

Tags:

c++

I have a previous question that was answered in which I describe difficulties catching an exception when I try to access an object that has been deallocated by a third-party function. The function sometimes does and sometimes doesn't deallocate the object.

In order to avoid having to use a try/catch block to catch the SEH Exception as described in the previous question, I need to be able to tell whether the object has been deallocated or not.

How can I determine if a C++ object has been deallocated or is still a valid pointer?

like image 703
Michael Bray Avatar asked Sep 03 '09 15:09

Michael Bray


2 Answers

You can't easily tell just by looking at the memory location if the object is still allocated or not. There might be some black magic tricks to do that, but a much cleaner way would be to build a call-back mechanism into the object's destructor.

like image 96
Adrian Grigore Avatar answered Oct 13 '22 20:10

Adrian Grigore


I think you're asking the wrong question. The question really ought to be:

Why do I feel like I need to look at some address in order to find out whether the pointer pointing there refers to an object or to the garbage left after an ex-object was deleted?

Honestly, you shouldn't be in that situation. If an object is deleted, why are you left with a pointer to its ex-address? Ideally, the pointer should be out of scope. If that isn't possible in your code, it should have been set to NULL.

like image 36
sbi Avatar answered Oct 13 '22 21:10

sbi