Tuesday, December 7, 2010

Memory Leak Detection and Isolation - Part1: Enabling MemoryLeakDetection

Tip - Visual Studio debugger and C run-time (CRT) libraries provide you with effective means for detecting and identifying memory leaks.
Details -The primary tools for detecting memory leaks are the debugger and the C Run-Time Libraries (CRT) debug heap functions.
To enable the memory leak detection on heap, add following piece of code in your program. For this make sure that your code is _DEBUG enabled.
#include <stdlib.h>
#include <crtdbg.h>
Next step is to insert _CrtSetDbgFlag ( _CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF ) to your main function of your application.
Now your application is ready to detect memory leak and it will display the logs in output window of your debugger or use Dbgview.exe . For release version, you required to enable _DEBUG preprocessor. A sample log look like as below.

Technique behind this is to use _malloc_dbg() and _free_dbg() instead of malloc() and free(). So that it is able to keep track of memory allocation and deletion. When we use CRT debug methods, compiler will use _malloc_dbg() and _free_dbg() for heap managing.
Note: You can manually dump the log using _CrtDumpMemoryLeaks() API. But remember that the destructors for any variables you declared at runtime (i.e. any variables declared not using the 'new' operator) have *NOT* been called yet. This makes the memory holding these variables look like leaked memory when in fact the memory will be cleaned up just prior to program exit. So highly recommended method is to use _CrtSetDbgFlag ( _CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF );
Reference    :

Posted By :Krishnaraj S.

No comments:

Post a Comment