commedo's blogger

Saturday, June 19, 2004

[PROGRAMMING TIPS] Detecting memory leak (MSVC)

Microsoft provided library CRTDBG to detect memory leak in source code. Here is an example how to detect memory leak using CRTDBG:


#include <stdio.h>

#ifdef _DEBUG
#include <crtdbg.h>
#include <string.h>
#include <malloc.h>
#define SET_CRT_DEBUG_FIELD(a) _CrtSetDbgFlag((a) | _CrtSetDbgFlag(_CRTDBG_REPORT_FLAG))
#define CLEAR_CRT_DEBUG_FIELD(a) _CrtSetDbgFlag(~(a) & _CrtSetDbgFlag(_CRTDBG_REPORT_FLAG))
#else
#define SET_CRT_DEBUG_FIELD(a) ((void) 0)
#define CLEAR_CRT_DEBUG_FIELD(a) ((void) 0)
#endif

int main(int argc, char *argv[])
{
// variable
char *p;

#ifdef _DEBUG
_CrtMemState s1, s2, s3;
_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 );
_CrtMemCheckpoint( &s1 );
#endif

// do some work here
p = (char *)malloc(sizeof(char)*100);
strcpy(p,"Hello world");
printf("%s\n",p);
//free(p); // Seolah2 kita lupa mem-free

#ifdef _DEBUG
_CrtMemCheckpoint( &s2 );
if ( _CrtMemDifference( &s3, &s1, &s2 ) ){
printf("\n------------\nOuups! leak detection.\n");
_CrtMemDumpStatistics( &s3 );
}else{
printf("\n------------\nCongratulation! no leak detection.\n");
}
#endif
return 0;
} // end of main

Use option /MTd to compile the code, e.g. cl memdetect.c /MTd

1 Comments:

  • Although I enjoyed beingwith women, deep down I still preferred men. COLLINS Hello.
    female dominant bondage stories
    stories of first time getting fucked
    free erotic girdle stories
    xnxx sex stories
    free adult comic stories
    Although I enjoyed beingwith women, deep down I still preferred men. COLLINS Hello.

    By Anonymous true first time lesbian experience stories, at December 4, 2010 at 7:34 PM  

Post a Comment

<< Home