Watch out for that Memory Leak by Blake Madden

The problem:  You allocated a block of memory on the free store (heap) and you forgot to free it back to the system when you're done with it.  Because of this, that block of memory is gone for good (unless you reboot). 

Here's a pseudo-code example: 
int main()
{
objectFactory();
return 0;
}

void ObjectFactory()
{
CObject* pObject = new CObject*;
}
As you can see, the object is created in the  ObjectFactory() function, but its memory is never returned to the system.  Here is one way of doing that: 

int main()
{
ObjectFactory();
return 0;

void ObjectFactory()
{
CObject* pObject = new CObject*;
delete pObject;

As you can see, the keyword delete free the block of memory back up.  However, you weren't able to get a chance to use the new Object.  Here's a way that you can create it in one function, pass it to main, and delete from main later:

int main()
{
CObject* pNewObject = ObjectFactory();
pNewObject->DoSomeFunction();
delete pNewObject;
return 0;
}

CObject* ObjectFactory()
{
CObject* pObject = new CObject*;
return  pObject;
}

or here's another way:

CObject* pNewObject = 0; //global pointer to a CObject, not valid right now.
int main()
{
CObject* pNewObject = ObjectFactory();
pNewObject->DoSomeFunction();
delete pNewObject;
return 0;
}

void ObjectFactory()
{
pNewObject = new CObject*;  //assign the address of a dynamic CObject to the global pointer
}

A good rule of thumb is that there should be a delete for every new (or a free() for every malloc() if you are using C).  Dynamic blocks of memory don't clean up after themselves when they go out of scope the way that classes do (because of destructors), so be sure to always match up your news and deletes.  One last point to make is that you should never delete something twice.  Rather than not doing anything (since the item has already been freed from memory), another block of data will be freed.  This will lead to overwriting other data on your system and is quite problematic.

Add your tutorials to this site Mail Me

 

Google
  Web www.gauravcreations.com

GauravCreations's Store / Home / Register / Awards / Opinions / Downloads / Query

Linux Hosting India | Linux Forum

Copyright © 2001-04 [Gaurav Creations]. All rights reserved