Question

In a Visual C++ program, I am calling delete on a pointer. I will later need to check if the pointer has been deleted. I've noticed Visual C++ will set the address to 0x00000000, but later that value might be changed to something like 0xABABABAB, 0xFEEEFEEE, or some other value such as that. Checking for NULL only works on 0x00000000 addresses.

Is there a reliable way that I can check if the pointer was deleted, regardless of these changes the address may undergo?

Was it helpful?

Solution

If you are deleting a pointer to an object, you can see the destructor. If you want to know whether memory free operation was performed or not, there is no reliable/portable way to know this. Memory management is implementation dependant. Even this is possible that memory freeing is deferred by the library. But you should always believe that delete never fails. And if you have not overloaded delete operator, you can rely on libraries that memory would be released.

About memory contents, after contents being freed, you should not access them as the behaviour is undefined.

If you want this for debugging purpose, I would suggest using some alternate technique.

If you want to know whether pointer was freed, you should explicitly set it to 0, and you can later compare pointer with 0 to check whether it was freed.

if (...) {
  delete ptr;
  ptr = 0; // set explicitly
}
...
if(0 == ptr) {
  // Pointer was freed
  ...
} else {
  // Pointer was not freed
  ...
}

OTHER TIPS

If you use C++11 you can just set the value of the pointer to nullptr and test for that afterwards (like if (foo == nullptr)).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top