问题描述
有人知道一种技术来发现智能指针引起的内存泄漏吗?我目前正在编写一个大型项目,写在 C ++ ,大量使用智能指针与引用计数。显然,我们有一些由智能指针引起的内存泄漏,它们仍然在代码中被引用,使得它们的内存不会被释放。很难找到带有不需要引用的代码行,导致相应的对象不被释放(虽然它不再使用了)。
Does anybody know a "technique" to discover memory leaks caused by smart pointers? I am currently working on a large project written in C++ that heavily uses smart pointers with reference counting. Obviously we have some memory leaks caused by smart pointers, that are still referenced somewhere in the code, so that their memory does not get free'd. It's very hard to find the line of code with the "needless" reference, that causes the corresponding object not to be free'd (although it's not of use any longer).
我在网络中找到一些建议,建议收集参考计数器的增量/减量操作的调用堆栈。这给了我一个很好的提示,哪段代码导致引用计数器增加或减少。
I found some advice in the web, that proposed to collect call stacks of the increment/decrement operations of the reference counter. This gives me a good hint, which piece of code has caused the reference counter to get increased or decreased.
但我需要的是某种算法, 一起增加/减少调用堆栈。删除这些调用堆栈后,我希望有(至少)一个增加调用堆栈剩余,显示我有不需要引用的代码片段,导致相应的对象不被释放。现在没有什么大不了解的漏洞了!
But what I need is some kind of algorithm that groups the corresponding "increase/decrease call stacks" together. After removing these pairs of call stacks, I hopefully have (at least) one "increase call stack" left over, that shows me the piece of code with the "needless" reference, that caused the corresponding object not to be freed. Now it will be no big deal to fix the leak!
但是有人有一个想法,一个算法做分组?
But has anybody an idea for an "algorithm" that does the grouping?
开发在 Windows XP 下进行。
(我希望有人明白,我试图解释... )
(I hope someone understood, what I tried to explain ...)
EDIt:我在谈论由循环引用引起的泄漏。
EDIt: I am talking about leaks caused by circular references.
推荐答案
请注意,具有引用计数智能指针的一个泄漏源是循环依赖性的指针。例如,A有一个指向B的智能指针,B有一个指向A的智能指针.A和B都不会被销毁。
Note that one source of leaks with reference-counting smart pointers are pointers with circular dependancies. For example, A have a smart pointer to B, and B have a smart pointer to A. Neither A nor B will be destroyed. You will have to find, and then break the dependancies.
如果可能,使用boost智能指针,并使用shared_ptr作为应该是数据所有者的指针,而weak_ptr用于不应调用delete的指针。
If possible, use boost smart pointers, and use shared_ptr for pointers which are supposed to be owners of the data, and weak_ptr for pointers not supposed to call delete.
这篇关于查找由智能指针造成的内存泄漏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!