代码之家  ›  专栏  ›  技术社区  ›  Carbon

CRT不打印内存泄漏的行号

  •  3
  • Carbon  · 技术社区  · 7 年前

    Finding Memory Leaks Using the CRT Library ,应打印出内存泄漏的行号。

    #include "stdafx.h"
    #define _CRTDBG_MAP_ALLOC
    #include <stdlib.h>
    #include <crtdbg.h>
    #include <iostream>
    
    
    void derp()
    {
        int* q = new int;
    
    }
    
    int main()
    {
        _CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF);
        derp();
        return 0;
    }
    

    Detected memory leaks!
    Dumping objects ->
    {75} normal block at 0x0067E930, 4 bytes long.
     Data: <    > CD CD CD CD 
    Object dump complete.
    

    根据微软的文档,我希望看到泄漏内存分配线的打印结果,但我没有。

    我做错了什么?我正在使用VS2015。

    3 回复  |  直到 7 年前
        1
  •  6
  •   Edgar Rokjān    7 年前

    MSDN topic :

    这些技术适用于使用标准CRT分配的内存 但是,您可能只能看到 全局运算符新调用_malloc\u dbg在 将其更改为使用宏报告进行分配的行 看起来是这样的:

    #ifdef _DEBUG
        #define DBG_NEW new ( _NORMAL_BLOCK , __FILE__ , __LINE__ )
        // Replace _NORMAL_BLOCK with _CLIENT_BLOCK if you want the
        // allocations to be of _CLIENT_BLOCK type
    #else
        #define DBG_NEW new
    #endif
    

    new 在代码中使用 DBG_NEW 。我测试了它,它与您的代码正常工作。


    具有 DBG_新 代码中的任何地方都是一项非常繁琐的任务,因此您可能需要使用以下宏:

    #ifdef _DEBUG
         #define new new( _NORMAL_BLOCK , __FILE__ , __LINE__ )
    #else
         #define new new
    #endif
    

        2
  •  2
  •   Chris Sprague    7 年前

    查看答案 here 。您想使用重载 new

    int* q = new int;
    

    int* q = new (_NORMAL_BLOCK, __FILE__, __LINE__) int;
    

    你应该看到漏洞。

        3
  •  0
  •   Swift - Friday Pie    7 年前

    “这些技术适用于使用标准CRT分配的内存 malloc函数。如果您的程序使用C++新 但是,如果希望看到

    结果,您将获得新运算符定义的行。您可以使用new可以接受额外参数的技巧,其中一些参数可以默认为宏定义的值,例如 __LINE__ __FILE__