How to check when a pointer is deleted?

When I debug someone else's code, how can I find when a pointer is deleted?

+6
source share
6 answers

1)

Use a debugger. perform one uninstall. In general, you find yourself in some kind of "free" function that passes a pointer

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

2)

One such approach is to override the delete method and check this pointer.

3)

If the pointer refers to an object with a destructor. Place a breakpoint on the destructor. Maybe you want to add a destructor first (if this is possible at all using external code, it is always possible by native code)

+5
source

Set a conditional breakpoint on the destructor of the appropriate type. Let the this condition indicate the object of interest to you. For example, in Visual C ++ Express 2010:

enter image description here

For the above figure, I first performed after three new expressions, then marked the address of object b , and then used it as a break condition that this should be this address.

Information on how to do this with other debuggers depends on the debugger. See the debugger manual.

+3
source

In C ++, you do not have a built-in cross-platform function that will detect if the pointer is deleted.

However, you can use the tools provided by some debuggers, tools, and the language itself. For example, you can overload the new and delete operator globally and / or based on each class and support a common link type / map type. eg:.

 class X { ... set<void*> m_CurrentAlloc; public: void* operator new (size_t SIZE) { ... m_CurrentAlloc.insert(p); return p; } void operator delete (void *p) { m_CurrentAlloc.erase(p); ... } }; 

At periodic bases or at the end of a program, the contents of this set can be printed or verified.
Remember that this is the solution for the ideal situation when you are doing memory management with new/delete . If you have a combination of malloc/free , then the code also needs other improvements.

+1
source

What about the gdb watchpoint ? You can set the observation point on the pointer in question and see when the program addresses the removal of its referent.

0
source

If you are accessing the memory pointed to by a pointer, you cannot. However, if you are having problems with dangling pointers, just replace all of their original boost :: shared_ptr pointers and delete all occurrences of free ones and delete. Never use deleted or free keywords. Smart rock pointers!

0
source

You can not. Use smart pointers and don't worry about it.

-1
source

Source: https://habr.com/ru/post/916737/


All Articles