0

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?

Community
  • 1
  • 1
Oliver Spryn
  • 16,871
  • 33
  • 101
  • 195
  • 1
    There's no reliable, portable way to do this in standard C++. – juanchopanza May 11 '14 at 06:51
  • You can't rely on things like that to decide whether `delete` has been called on a pointer. – R Sahu May 11 '14 at 06:51
  • i hope this question helps you http://stackoverflow.com/questions/4990462/what-happens-to-an-address-after-delete-operator-has-been-applied-to-it-in-c – WileTheCoyot May 11 '14 at 07:45
  • @spryno724 The problem is not entirely clear. Is it (a) You *know* that your program invokes `delete` on your pointer but you want to check later *if the deletion has really happened*? Or (b) You *believe* that your program invokes `delete` on your pointer but perhaps in some circumstances it doesn't, and you want to make sure? – Mike Kinghan May 11 '14 at 10:53

2 Answers2

2

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
  ...
}
Mohit Jain
  • 30,259
  • 8
  • 73
  • 100
0

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

  • Why the -1? I don't see why this would be wrong. Signed, Everyone Who Isn't Very Familiar with C++11 standard. – josaphatv May 11 '14 at 07:01
  • @josaphatv I thought it was blindingly obvious. So here it goes: This is not a C++11 specific problem (and the same can be achieved in C++03), and in any case it doesn't answer the question. OP needs the deleted pointer to point to some recognizable address, meaning they don't want to set the pointer manually. – juanchopanza May 11 '14 at 07:05