By using visual studio debugger and crt debug heap functions, it’s possible to detect the memory leak in your application
The following code will enable debug heap functions in your application
#define _CRTDBG_MAP_ALLOC
#include
#include
By including crtdbg.h malloc and free functions will be replaced to their debug versions, _malloc_dbg and _free_dbg. This will keep track of your memory allocation and deallocation.
To get the memory leak information, we can use _CrtDumpMemoryLeaks(); function whenever required
E.g:
#define _CRTDBG_MAP_ALLOC
/* _CRTDBG_MAP_ALLOC is to get the extended information on error reporting. This is actually optional */
#include
void Allocate()
{
int * pIntArray = new int[100];
}
int _tmain(int argc, _TCHAR* argv[])
{
int * pIntArray = new int[100];
for ( int i = 0; i < 5 ; i++ )
Allocate();
_CrtDumpMemoryLeaks(); // Dump memory leak information
return 0;
}
Alternate method to automatically invoke “_CrtDumpMemoryLeaks();” on program exit
You can call _CrtSetDbgFlag ( _CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF ); function as specified in the beginning of your program. This will automatically call CrtDumpMemoryLeaks(); function on program exit
#define _CRTDBG_MAP_ALLOC
#include
void Allocate()
{
int * pIntArray = new int[100];
}
int _tmain(int argc, _TCHAR* argv[])
{
// Call this in th beginning of program
_CrtSetDbgFlag ( _CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF );
int * pIntArray = new int[100];
for ( int i = 0; i < 5 ; i++ )
Allocate();
return 0;
}
Check MSDN for more information