获取在堆上分配的块数量,以检测内存泄漏

Get number of blocks allocated on the heap to detect memory leaks

本文关键字:检测 泄漏 内存 分配 获取      更新时间:2023-10-16

是否有可用的函数可以获得当前在堆上分配的内存块数量?它可以是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宏链接)