当我调试别人的代码时,我怎么能发现指针被删除了?
6 回答
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)
在相关类型的析构函数上设置条件断点。让条件this
指向您感兴趣的对象。例如,在 Visual C++ Express 2010 中:
上图我先执行到三个new
表达式之后,然后记下b
对象的地址,然后作为断点条件,this
应该是那个地址。
如何使用其他调试器执行此操作的详细信息取决于调试器。请参阅调试器的手册。
在 C++ 中,您没有任何内置的跨平台功能,它会发现指针是否被删除。
但是,您可以使用某些调试器、工具和语言本身提供的功能。例如,您可以全局和/或在每个类基础上重载new
anddelete
运算符,并维护一个通用的集合/映射类型的引用。例如:
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
那么代码也需要其他增强功能。
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.
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!
You can't. Use smart pointers and never worry about it.