Software Technology Tips

Its a good practise if we don't depend on IDE/third-party tools/software to detect memory leaks in our code. Its better if we can predict before hand the consequences of writing each line of code. 
 
But there may be situations where we need to work on projects written by someone else. In such cases these third-party tools may help us in finding a QUICK solution.
 
The visual studio debugger along with C run-time (CRT) libraries provides us means for detecting memory leaks.But its capabilities are minimal.
 
Enabling memory leak detection in visual studio:

1. If our program can exit from multiple locations, instead of putting a call to _CrtDumpMemoryLeaks at each possible exit,include the following call at the beginning of program:
_CrtSetDbgFlag( _CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF);

This statement automatically calls _CrtDumpMemoryLeaks when program exits.

2 . The macro  _CRTDBG_MAP_ALLOC applies to c library functions malloc, realloc.With a little bit of extra code, we can get it to work with new/delete:

#define _CRTDBG_MAP_ALLOC

#include <iostream>
#include <crtdbg.h>

#ifdef _DEBUG
#define DEBUG_NEW new(_NORMAL_BLOCK, __FILE__, __LINE__)
#define new DEBUG_NEW
#endif

These macros should be added after including all other header files.

3. By default, _CrtDumpMemoryLeaks dumps memory leak information to the Output window,we can reset this to a file using _CrtSetReportMode. For doing this add the following lines of code at the starting of your program.

 HANDLE hLogFile;
 hLogFile = CreateFileA("c:\\memoryLeaksDump.rtf", GENERIC_WRITE,FILE_SHARE_WRITE, NULL, CREATE_ALWAYS,FILE_ATTRIBUTE_NORMAL, NULL);

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

 _CrtSetDbgFlag( _CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF);


Related Tags:

VC++

Author: Jyothi Sambolu

VC++

Let us Connect!

iso 9001 QA25 Red Herring STPI D&B Fastest Growing SME 2013 Award zinnov Nasscom

This site uses cookies. We respect your privacy.copyright (c) Mindfire Solutions 2007-2015. Login