Detect Memory Leaks in C++ Project using Visual Studio Express Edition

Whenever using Pointers in C++ there are chances of having memory leaks in the program. Pointers in C++ Projects allows programmer to allocate and free up memory as and when required. In case a C++ project allocates memory but does not releases it, then the C++ program is said to be causing memory leaks. The C++ Sample project presented here demonstrates how you have introduce memory leaks in your C++ program and how you can detect the memory leak in Visual Studio Express Edition.

C++ Sample Project to Cause and Detect Memory leaks

C++ Sample Project to Cause and Detect Memory leaks

As displayed in the above screenshot, the C++ program allocates memory for an integer variable but does not deletes it causing memory leaks. Note the line

#include <crtdbg.h>

has been added to the project and the first function call to _CrtSetDbgFlag ensures that whenever your program terminates, any memory leaks are displayed onto the output window of Visual Studio. The output of this sample C++ project is nothing but a memory leak of 4 bytes as displayed in the screenshot below.

Output Window of Visual Studio Express Edition Displays Memory Leaks

Output Window of Visual Studio Express Edition Displays Memory Leaks

It is not a good programming practice to leave memory leaks in your C++ projects. You must always allocate memory as and when needed and free it whenever you do not need the allocated memory. Microsoft recommend adding given below lines to the C++ project for detecting memory leaks.

#define _CRTDBG_MAP_ALLOC#include <stdlib.h>#include <crtdbg.h>

and in your C++ program execution you can request a memory check anytime by calling the given below function.

_CrtDumpMemoryLeaks();

The Complete Project Source Code of this Sample Project to introduce and detect memory leaks is as given below. Memory leaks needs to be considered whenever your C++ Project is using pointers to allocate and free up Class Objects. There are many other 3rd party software tools apart from Visual C++ which help developers of C++ Projects to find and isolate Memory Leaks.

#include "stdafx.h"//Add given below Lines to C++ Project#define _CRTDBG_MAP_ALLOC#include #include int _tmain(int argc, _TCHAR* argv[]){//Add This Line_CrtSetDbgFlag ( _CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF );//Your Program which can have memory leaksint* pOinterToInteger = new int;return 0;}