【问题标题】:_CRTDBG_MAP_ALLOC not showing file name_CRTDBG_MAP_ALLOC 不显示文件名
【发布时间】:2013-12-05 03:22:24
【问题描述】:

我正在尝试检测内存泄漏,并且我正在使用 make _CRTDBG_MAP_ALLOC 宏来定位泄漏区域的位置。所以我定义 MACRO 如下:

#ifdef _DEBUG
    #define _CRTDBG_MAP_ALLOC
#include <stdlib.h>
#include <crtdbg.h>
    #define DEBUG_NEW new(_NORMAL_BLOCK, __FILE__, __LINE__)
    #define new DEBUG_NEW
#endif

在我的代码中,我有:

UINT SomeFunThread( LPVOID pParam )
{
   _CrtMemState crtMemStateStart;
    _CrtMemState crtMemStateFinish;

    _CrtMemCheckpoint(&crtMemStateStart);


    // My suspisious code


     _CrtMemCheckpoint(&crtMemStateFinish);

      int nDifference(0);
      _CrtMemState crtMemStateDifference;
      nDifference = _CrtMemDifference(&crtMemStateDifference, &crtMemStateStart, &crtMemStateFinish);

    if(nDifference > 0)
        _CrtDumpMemoryLeaks();

    return 0;
}

(感谢 Tushar Jadhav:Memory consumption increases quickly, then drops very slowly; memory leak?

但输出显示如下:

Detected memory leaks!
Dumping objects ->
{124058} normal block at 0x0000000031DED080, 24 bytes long.
 Data: < 0      ` $     > C8 30 F7 EF FE 07 00 00 60 D2 24 1D 00 00 00 00 

而不是这样的:

Detected memory leaks!
Dumping objects ->
C:\PROGRAM FILES\VISUAL STUDIO\MyProjects\leaktest\leaktest.cpp(20) : {18} 
normal block at 0x00780E80, 64 bytes long.
 Data: <                > CD CD CD CD CD CD CD CD CD CD CD CD CD CD CD CD
Object dump complete.

那么我怎样才能让它显示泄漏的文件名和位置呢?

【问题讨论】:

  • 刚刚分配的代码没有使用您的#defines 编译。可以位于库中,也可以位于 DLL 中,例如预构建的 C++ 模板类特化。或者包含代码的 DLL 在生成泄漏报告之前被卸载。
  • @HansPassant 那么你是说不是我的“可疑代码”本身泄露了吗?是在“可疑代码”中调用了一些代码/bianraies/dll 吗?
  • 我会说这是你没有找到的代码,可能在任何地方。泄漏的常见问题,不是吗?如果您可以让 {braces} 之间的数字重复,则将 _crtBreakAlloc 设置为该数字。

标签: c++ debugging memory-leaks crtdbg.h


【解决方案1】:

似乎只有在该 cpp 文件中打开 CRT 时才会显示泄漏行。

【讨论】:

  • 有没有快速打开所有文件中的 CRT 的方法,例如创建一个包含定义的新标题并将其包含在任何地方?
  • 第二个 aquirdturtle 的问题:看起来我的软件中的所有代码都从包括“stdafx.h”开始,所以我在“TODO”注释之后添加了这三行,并重新构建。这还不够。 // TODO: reference additional headers your program requires here#define _CRTDBG_MAP_ALLOC#include &lt;stdlib.h&gt;#include &lt;crtdbg.h&gt;
【解决方案2】:

就我而言,我最终将this 线程中的内容包含到我的代码中。这将覆盖new 运算符并将文件名和行号包含在其中以供以后打印。不确定这是否仅适用于 Visual Studio。

#define _CRTDBG_MAP_ALLOC
#include <crtdbg.h>
#ifdef _DEBUG
#define DEBUG_NEW new(_NORMAL_BLOCK, __FILE__, __LINE__)
#define new DEBUG_NEW
#endif

来自引用源的整个测试代码是:

#define _CRTDBG_MAP_ALLOC
#include<iostream>
#include <crtdbg.h>
#ifdef _DEBUG
    #define DEBUG_NEW new(_NORMAL_BLOCK, __FILE__, __LINE__)
    #define new DEBUG_NEW
#endif

int main() 
{
    char *a = new char[10];
    _CrtDumpMemoryLeaks();
    return 0; 
}

在我的测试用例中打印:

Detected memory leaks!
Dumping objects ->
e:\test\testapplication\testapplication.cpp(11) : {144} normal block at 0x007F4EF0, 10 bytes long.
 Data: <          > CD CD CD CD CD CD CD CD CD CD 
Object dump complete.

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-04-05
    • 2019-10-08
    • 2015-01-20
    • 2020-08-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多