Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check when a pointer is deleted?

When I debugging someone else's code, how could I found when a pointer is deleted?

like image 789
Enze Chi Avatar asked May 26 '12 11:05

Enze Chi


People also ask

What happens when a pointer is deleted to is?

After pointer was deleted it is still pointing to same memory address. Use of that pointer can cause undefined behavior. Normally it will cause the memory access violation and call will be "trapped".

Does delete remove the pointer?

delete keyword in C++ Which means Delete operator deallocates memory from heap. Pointer to object is not destroyed, value or memory block pointed by pointer is destroyed. The delete operator has void return type does not return a value.

What happens if a pointer is deleted in C++?

delete on an already deleted non-null pointer is undefined behavior - your program will likely crash. You can safely use delete on a null pointer - it will yield a no-op.

Can this pointer be deleted?

Can you delete this pointer inside a class member function in C++? Answer: Yes, we can delete “this” pointer inside a member function only if the function call is made by the class object that has been created dynamically i.e. using “new” keyword.


2 Answers

1)

Use a debugger. follow one delete. In general you end up in some "free" function passing a pointer

Set a breakpoint with the condition that the past pointer has the same value as your investigated pointer

2)

One similar approach is to override the "delete" method and to check for that pointer in question.

3)

If the pointer refers to an object with an destructor. Place a breakpoint on the destructor. May be you may want to add a destructor first (if possible at all by foreign code, always possible on own code)

like image 74
stefan bachert Avatar answered Sep 24 '22 14:09

stefan bachert


Set a conditional breakpoint on the destructor of the type in question. Let the condition be that this points to the object you're interested in. E.g., in Visual C++ Express 2010:

enter image description here

For the above figure I first executed to after the three new expressions, then noted the address of the b object, and then used as breakpoint condition that this should be that address.

The details of how to do this with other debuggers depends on the debugger. See the debugger's manual.

like image 25
Cheers and hth. - Alf Avatar answered Sep 24 '22 14:09

Cheers and hth. - Alf