获取在堆上分配的块数量,以检测内存泄漏
Get number of blocks allocated on the heap to detect memory leaks
是否有可用的函数可以获得当前在堆上分配的内存块数量?它可以是Windows/Visual Studio特定的
我想用它来检查函数是否泄漏内存,而不使用专用的分析器。我在想这样的事情:
int before = AllocatedBlocksCount();
foo();
if (AllocatedBlocksCount() > before)
printf("Memory leak!!!");
有几种方法可以做到这一点(特定于Microsoft Visual Studio自带的CRT)
一种方法是在您感兴趣的调用之前和之后使用_CrtMemCheckpoint()
函数,然后比较与_CrtMemDifference()
的差异。
_CrtMemState s1, s2, s3;
_CrtMemCheckpoint (&s1);
foo(); // Memory allocations take place here
_CrtMemCheckpoint (&s2);
if (_CrtMemDifference(&s3, &s1, &s2)) // Returns true if there's a difference
_CrtMemDumpStatistics (&s3);
您还可以使用_CrtDoForAllClientObjects()
枚举所有分配的块,以及使用visualc++ CRT的调试例程的其他几个方法。
指出:
- 所有这些都在
<crtdbg.h>
头中。 - 它们显然只适用于Windows和VC编译。
- 你需要设置CRT调试和一些标志和其他东西。
- 这些是相当棘手的功能;请务必仔细阅读MSDN的相关部分。
- 这些仅在调试模式下工作(即与调试CRT和定义的
_DEBUG
宏链接)
相关文章:
- 如何在 Linux/MacOs 平台中检测到内存泄漏?
- 为什么 heob 在 QCreator 生成的代码中将这些检测为内存泄漏
- C++默认参数通过_CrtMemDifference屏蔽内存泄漏检测
- Valgrind检测到OpenGL内存泄漏
- 通用 Windows 平台上的内存泄漏检测
- 泄漏消毒剂检测泄漏
- Valgrind和Qemu-无法检测到内存泄漏
- 了解Microsoft的内存泄漏检测输出
- 通过附加到进程进行内存泄漏检测
- 检测到内存泄漏
- 地址清理器无法使用选项 -O 检测内存泄漏
- 如何在C++中编写一个小内存泄漏检测
- 为引用计数的智能指针检测内存泄漏的设计模式
- 如何检测窗口(gtk、qt等)应用程序上的内存泄漏
- CRT内存泄漏检测未检测到内存泄漏
- 如何在tbbmalloc中检测内存泄漏
- 检测到指针引用可能存在内存泄漏
- 在一个非常简单的程序中检测到内存泄漏.怎么办
- VC 2012 中的内存泄漏检测
- Valgrind 在 fclose() 处检测到内存泄漏