Wednesday 31 March 2010

Deleting of Vectors content to avoid memory leaks

Its interesting how deleting of vectors can sometimes be a problem as people tend to make simple mistakes that can cause crash and waste useful hours to debug.

The following code shows my approach to deleting of vectors. I am sure there are better approaches. In case you know one please share.




//Program tested on Microsoft Visual Studio 2008 - Zahid Ghadialy
//Program to demonstrate a simple way to delete vector and memory
//associated with it.

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

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

using namespace
std;

int
main()
{

_CrtSetDbgFlag( _CRTDBG_ALLOC_MEM_DF _CRTDBG_LEAK_CHECK_DF );
vector<int *> someVector;
for
(int i = 0; i < 5; i++)
{

int
* x = new int(i * 15);
someVector.push_back(x);
}


//now we need to delete the elements of the vector else it will generate memory leaks
//This is one simple and safe approach
while (!someVector.empty())
{

vector<int *>::iterator it = someVector.begin();
if
(*it) //Additional safety in case a NULL pointer was stored
delete (*it); //because *it = *int - Only the contents are deleted
someVector.erase(it);
}


return
0;
}





You can check my old post on how to see if memory leaks are there. This program shows another approach but the results are the same

No output needed.

You can read more about this approach of detecting memory leaks on the MSDN site here.

1 comment:

  1. Just use Deleaker ( http://deleaker.com/ ) to find all kinds of memory leaks in your app

    ReplyDelete