Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 779
Aslan986 Avatar asked Aug 01 '26 22:08

Aslan986


1 Answers

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

like image 99
Viktor Latypov Avatar answered Aug 03 '26 14:08

Viktor Latypov