如何通过 Valgrind 或其他工具检测 Qt 软件中的内存泄漏?
我已经用 Qt/C++ 开发了一个库,现在我想确定内存泄漏测试,
我发现了 Valgrind 并且似乎是一个很好的检测器(我仍然不使用它),但是还有另一个工具吗 用于测试内存泄漏?
I have developed a library with Qt/C++ and now I want to sure about memory leak testing,
I found Valgrind and seems a good detector(I still don't work with it), but is there another tool(s) for testing for memory leak?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
是的,正如 Als 在评论中指出的那样,根据我的个人经验,我还建议使用 valgrind。您可能会使用多种选项,例如
--leak-check=yes
等。运行 valgrind 后,它会输出一些推荐选项,您可以在下次运行中包含这些选项。Valgrind 正在尝试解决的问题,即查找内存泄漏,是一个复杂的问题。有时 valgrind 会感到困惑并输出误报,即它在没有内存泄漏的地方显示内存泄漏。但是,除此之外,valgrind 非常用户友好且有用。
Yes, as Als has pointed out in a comment and from my personal experience, I would also recommend going with valgrind. There are various options such as
--leak-check=yes
etc. that you might use. Once you run valgrind, it outputs some recommend options that you can include in the next run.The problem Valgrind is attempting, i.e., of finding memory leaks, is a complex problem. Sometimes valgrind gets confused and outputs false positives, i.e., it shows a memory leak at a place where there is none. But, other than this, valgrind is quite user-friendly and useful.
您可以自己进行内存泄漏检查,而无需太多额外的工作(取决于您的代码)。只需提供您自己的 new 和 delete 运算符版本即可。使用容器来存储在new中分配的每个内存地址。如果调用了delete,则将其从集合中删除。在程序结束时,检查集合是否为空。
详细信息可参见 Scott Meyers 的书《Effective C++》,第 50 条。
You could do the memory leak check yourself without much additional affort (depending on your code). Just provide your own versions of the operators new and delete. Use a container to store each memory address that is assigned within new. Remove it from the collection if delete is called. At the end of your program, check if the collection is empty.
Details can be e.g. found in Scott Meyers book Effective C++, Item 50.