Aslan986
Aslan986

Reputation: 10324

C++ on Windows: function to get allocated memory?

I'm coding in C++, using Visual Studio 2008 on Windows 7.

My application have a memory leak, I can see it with the system monitor.

I need to discovery it in the code.

Does it exist a function that return the amount of memory allocated to the calling process?

Upvotes: 3

Views: 357

Answers (1)

Viktor Latypov
Viktor Latypov

Reputation: 14467

There is a MSVC-specific solution to memleak detection

// enable memory leaks detection
#if !defined(NDEBUG)
HANDLE hLogFile = CreateFile( "log.txt", GENERIC_WRITE, FILE_SHARE_WRITE,
                              NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL );
#endif

_CrtSetReportMode( _CRT_ASSERT, _CRTDBG_MODE_FILE | _CRTDBG_MODE_WNDW  | _CRTDBG_MODE_DEBUG );
_CrtSetReportMode( _CRT_WARN, _CRTDBG_MODE_FILE   | _CRTDBG_MODE_DEBUG );
_CrtSetReportMode( _CRT_ERROR, _CRTDBG_MODE_FILE  | _CRTDBG_MODE_WNDW  | _CRTDBG_MODE_DEBUG );

_CrtSetReportFile( _CRT_ASSERT, hLogFile );
_CrtSetReportFile( _CRT_WARN,   hLogFile );
_CrtSetReportFile( _CRT_ERROR,  hLogFile );

int tmpDbgFlag = _CrtSetDbgFlag( _CRTDBG_REPORT_FLAG );
tmpDbgFlag |= _CRTDBG_ALLOC_MEM_DF;
tmpDbgFlag |= _CRTDBG_DELAY_FREE_MEM_DF;
tmpDbgFlag |= _CRTDBG_LEAK_CHECK_DF;
_CrtSetDbgFlag( tmpDbgFlag );

if ( BlockIndex > 0 )
{
    _CrtSetBreakAlloc( BlockIndex );
}

This creepy code enables file protocol of all the unallocated blocks. Of course, it is deeply tied with the debug version of MSVCRT

Upvotes: 4

Related Questions