Why is _CrtDumpMemoryLeaks reporting a memory leak

2019-04-09 00:27发布

问题:

I want to check for memory leak in DEBUG mode. I use Windows and, to do this work, the function _CrtDumpMemoryLeaks.

Now, why this code finds a memory leak?

#include <Windows.h>
#include <iostream>

int main()
{
    if(_CrtDumpMemoryLeaks() == TRUE)
        std::cerr << "MEMORY LEAK!" << std::endl;

    return 0;
}

EDIT:

I add this code to direct output to console:

_CrtSetReportMode( _CRT_WARN, _CRTDBG_MODE_FILE );
_CrtSetReportFile( _CRT_WARN, _CRTDBG_FILE_STDOUT );
_CrtSetReportMode( _CRT_ERROR, _CRTDBG_MODE_FILE );
_CrtSetReportFile( _CRT_ERROR, _CRTDBG_FILE_STDOUT );
_CrtSetReportMode( _CRT_ASSERT, _CRTDBG_MODE_FILE );
_CrtSetReportFile( _CRT_ASSERT, _CRTDBG_FILE_STDOUT );

The output is:

回答1:

Did you include <crtdbg.h> ?

Are you sure you are running in debug mode?

In non-debug mode - the calls to _CrtDumpMemoryLeaks() are removed by the pre-processor leaving just if(TRUE)

EDIT: Also to detect memory leaks you need to add the below lines to use the debug versions of malloc and free - see here. Can you try adding these?

#define _CRTDBG_MAP_ALLOC
#include <stdlib.h>
#include <crtdbg.h>