Memory leaks

Hello! I'm a bit confused about basic C++ develpment.  
I have a class called CBox and one of its attributes is CExampleClass* pClass; I
attribute NULL to this pointer in CBox constructor.
Somewhen in running time, I call a method (called CBox::setPointer() for example)
and in its scope I write the line below:
pClass = new CExampleClass();
I don't delete it in the end of this routine (delete pClass) but keep on using
this pointer in the other methods that are called soon afterwards.  
I write the line in the CBox class destructor:
if (pClass != NULL) delete pClass;

I thought this would prevent from memory leaks but it didn't.  What is the problem?

Who is Participating?
mandhjoConnect With a Mentor Commented:
Is it possible that SetPointer is being called more than once for the same object?  This can be determined by putting logic in SetPointer that says...

if (pClass != NULL)
   TRACE("Oops, called it more than once);
   pClass = new CExampleClass();

This is a fairly standard technique that should work.

Does the destructor get called correctly? Pu a break point on it & see if the delete is called.

A note on technique: it may be better to use an auto_ptr member & create the CExampleClass instance in your constructor initialiser list. The auto_ptr will take care of freeing the CExampleClass.


class CBox
  auto_ptr<CExampleClass> m_pClass;

CBox::CBox() : m_pClass(new CExampleClass)
as mandhjo says, maybe you are calling SetPointer more than once. You should add an assert, such as ASSERT(pClass == NULL) in order to prevent this kind of errors.
Otherwise, the memory leak could be from somewhere else. Maybe CExampleClass is allocating something that isn't being destroyed?
What does your debug info. say. run the application in debug, at the end of the application your debug window will indicate which pointer is not getting deallocated.
marakrAuthor Commented:
You were right. I've checked and I was calling SetPointer multiple times.
All Courses

From novice to tech pro — start learning today.