简体   繁体   English

枚举分配的对象

[英]Enumerate allocated objects

How do I enumerate all allocated objects (allocated by the new operator) (not only those which have their own memory mappings, but those which are on the heap, too?) in C++? 如何在C ++中枚举所有分配的对象(由new运算符分配)(不仅具有自己的内存映射的那些对象,而且还具有堆上的那些对象?)?

I need this to find memory leaks. 我需要这个来查找内存泄漏。

Platform: Linux, gcc, i386,AMD_K64 (better: Platform independent) 平台:Linux,gcc,i386,AMD_K64(更好:与平台无关)

There may be no official way, but there may be a lean workaround. 可能没有官方的方法,但是可能有一个精益的解决方法。 For example, is there some internal variable you could access? 例如,您可以访问一些内部变量吗? Maybe a pointer to the list used for management of the heap? 也许是指向用于堆管理的列表的指针?

You always can use valgrind to check for memory leaks. 您始终可以使用valgrind检查内存泄漏。 Either install it with your package manager or just download and compile from: http://valgrind.org/ 可以使用软件包管理器进行安装,也可以直接从以下网址下载并进行编译: http//valgrind.org/

If you compile your application in debug mode it can pinpoint down to the file/line where you have allocated resources that were not freed/deleted. 如果您在调试模式下编译应用程序,则可以精确定位到分配了未释放/删除的资源的文件/行。

您可以使用valgrind来实现您想要的功能(将malloc替换为其自己的实现)并计算分配/释放

There are potentially two forms of memory lose 可能有两种形式的内存丢失

  1. Memory that was allocated, but it is no longer referenced from any place... and so it will not be possible to delete it. 已分配的内存,但是不再可以从任何地方引用它...因此将无法删除它。 This is a proper leak . 这是适当的泄漏 In Linux, the main tool of choice is valgrind . 在Linux中,选择的主要工具是valgrind Valgrind is a framework for multiple tools. Valgrind是多种工具的框架。 The tool you would be after is memcheck .... This is a dynamic analysis tool that will report about leaks and other memory problems. 您需要使用的工具是memcheck ...。这是一个动态分析工具,它将报告有关泄漏和其他内存问题的信息。 This goes further than enumerating the memory allocated, but it also needs to check whether it is still referenced or not. 这比枚举已分配的内存更进一步,但是还需要检查它是否仍在被引用。
  2. Memory that was allocated and it is still referenced, but somehow you've forgotten about it (eg vectors that grow endlessly because no-one never removes from them). 分配的内存仍在引用,但您却以某种方式忘记了它(例如,向量不断增长,因为没有人永远不会从中删除它们)。 This is where you need a tool for telling you the composition of all the memory you've allocated. 在这里,您需要一个工具来告诉您已分配的所有内存的组成。 Again valgrind can help you here. valgrind同样可以在这里为您提供帮助。 The tool this time is called massif 这次的工具叫做Massif

I'm sure there are more tools out there. 我确定那里还有更多工具。 These are pretty popular. 这些很受欢迎。

In Solaris, I'd recommend libumem for leak tracking and analyzer in Sun's Studio for profiling and memory analysis. 在Solaris中,我建议libumem用于Sun Studio中的泄漏跟踪和分析器,以进行性能分析和内存分析。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM