7

当我调试别人的代码时,我怎么能发现指针被删除了?

4

6 回答 6

5

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)

于 2012-05-26T11:24:22.973 回答
4

在相关类型的析构函数上设置条件断点。让条件this指向您感兴趣的对象。例如,在 Visual C++ Express 2010 中:

在此处输入图像描述

上图我先执行到三个new表达式之后,然后记下b对象的地址,然后作为断点条件,this应该是那个地址。

如何使用其他调试器执行此操作的详细信息取决于调试器。请参阅调试器的手册。

于 2012-05-26T12:05:00.620 回答
1

在 C++ 中,您没有任何内置的跨平台功能,它会发现指针是否被删除。

但是,您可以使用某些调试器、工具和语言本身提供的功能。例如,您可以全局和/或在每个类基础上重载newanddelete运算符,并维护一个通用的集合/映射类型的引用。例如:

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

在定期基础上或在程序结束时,set可以打印或验证其内容。
请记住,这是理想情况下的解决方案,您正在使用new/delete. 如果您也有混合,malloc/free那么代码也需要其他增强功能。

于 2012-05-26T12:10:42.297 回答
0

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.

于 2012-05-26T11:26:28.383 回答
0

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!

于 2012-05-26T11:28:54.573 回答
-1

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

于 2012-05-26T11:30:27.100 回答