Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 272
Carbon Avatar asked Oct 20 '25 13:10

Carbon


2 Answers

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.

like image 75
ikleschenkov Avatar answered Oct 22 '25 04:10

ikleschenkov


Check out the answer here. You want to use overloaded new operator with the additional parameters as specified in the solution there in order to get that information.

In this case, change your line

int* q = new int;

to

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

and you should see the leaks.

like image 32
Chris Sprague Avatar answered Oct 22 '25 05:10

Chris Sprague



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!