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

时间:2013-03-27 14:56:13

标签: c++ visual-studio memory-leaks

是否有可用的函数可以获取当前在堆上分配的内存块数量?它可以是Windows / Visual Studio特定的。

我想用它来检查函数是否泄漏内存,而不使用专用的分析器。我正在考虑这样的事情:

int before = AllocatedBlocksCount();
foo();
if (AllocatedBlocksCount() > before)
    printf("Memory leak!!!");

1 个答案:

答案 0 :(得分:2)

有几种方法可以执行此操作(特定于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()枚举所有已分配的块,以及使用Visual C ++ CRT的调试例程的其他几种方法。

注意:

  • 所有这些都在<crtdbg.h>标题中。
  • 它们显然只适用于Windows以及使用VC进行编译时。
  • 您需要设置CRT调试和一些标志和其他东西。
  • 这些是相当棘手的功能;请务必仔细阅读MSDN的相关部分。
  • 这些 only 在调试模式下工作(即与调试CRT和定义的_DEBUG宏链接。)