Slicer3:Memory Management

From NAMIC Wiki
Revision as of 21:19, 5 January 2007 by Millerjv (talk | contribs)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to: navigation, search
Home < Slicer3:Memory Management

This page discusses strategies writing and debugging code in Slicer3 such that you avoid memory leaks and double deletes.

What is a memory leak?

Memory leaks occur when a section of code allocates a block of memory that is never reclaimed.

void MyFunction()
{
   short *buffer = new short[1000]; // this memory is leaked!
}

How does memory get deleted multiple times?

A frequent problem with passing pointers from routine to routine is that it becomes very easy to loose track of which routine is responsible for deleting the block of memory. APIs rely on their documentation to educate the developers as to whether the developer is responsible for deleting the memory.

short *buffer = mykit::CreateBuffer(1000);
...
myKit::CleanUp();
...
delete [] buffer; // did myKit::CleanUp() already delete this memory?

Reference Counting

VTK and ITK both use reference counting to keep track of outstanding references to an object and automatically delete an object when it is no longer needed. VTK does with via calls to New()/Delete() and Register()/UnRegister() to increase and decrease the number of references to an object. If a function call returns a pointer to an object, the caller can choose to keep a long term handle to that object by increasing the reference count. The caller is responsible for decreasing the reference count when they no longer need the object.

MyClass::Function1()
{
   this->SomeObject = MyOtherClass::GetObject();
   this->SomeObject->Register( this );
}
MyClass::~MyClass()
{
   if (this->SomeObject)
     {
     this->SomeObject->UnRegister();
     this->SomeObject = 0;
     }
}


Stack-based coding

One way to avoid memory leaks

SmartPointers