Search code examples
c++memory-leakscrt

CRT Doesn't print line number of memory leak


I've got the code below, which I think, based on Finding Memory Leaks Using the CRT Library, should print out the line number of a memory leak.

#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;
}

When I run it, I get the following:

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

Based on Microsoft's documentation, I'd expect to see a print-out of the line where the leaky memory was allocated, but I don't.

What have I done wrong? I'm using VS2015.


Solution

  • From the MSDN topic:

    These techniques work for memory allocated using the standard CRT malloc function. If your program allocates memory using the C++ new operator, however, you may only see the file and line number where the implementation of global operator new calls _malloc_dbg in the memory-leak report. Because that behavior is not very useful, you can change it to report the line that made the allocation by using a macro that looks like this:

    #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
    

    And then replace the new in your code with DBG_NEW. I tested it and it works correctly with your code.


    Actually, replacing the new with DBG_NEW everywhere in the code is too tedious task, so possibly your could use this macro:

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

    I tested this method and it works too.