Enze Chi
Enze Chi

Reputation: 1763

How to check when a pointer is deleted?

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

Upvotes: 8

Views: 6055

Answers (6)

iammilind
iammilind

Reputation: 69998

In C++ you don't have any inbuilt cross platform feature, which will find whether a pointer is deleted or not.

However, you can use the facilities provided by some debuggers, tools and the language itself. For example you can overload the new and delete operator globally and/or on per class bases and maintain a common set/map kind of reference. e.g.:

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

On periodic bases or at end of the program the contents of this set can be printed or verified.
Remember that this is a solution for an ideal situation, where you are doing memory management using new/delete. If you are having mix of malloc/free too then code need other enhancements too.

Upvotes: 1

Cheers and hth. - Alf
Cheers and hth. - Alf

Reputation: 145279

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.

Upvotes: 4

Puppy
Puppy

Reputation: 146940

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

Upvotes: -1

stefan bachert
stefan bachert

Reputation: 9606

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)

Upvotes: 5

learnvst
learnvst

Reputation: 16195

If you are referring to the memory pointed to by a pointer, you can't. However, if you are having trouble with dangling pointers, just replace all of their raw pointers with boost::shared_ptr and remove all occurences of free and delete. Never use the delete or free keywords. Smart pointers rock!

Upvotes: 0

Chris Hayden
Chris Hayden

Reputation: 1144

How about a GDB watchpoint? You can set a watchpoint on the pointer in question and see when the program accesses to delete its referent.

Upvotes: 0

Related Questions