[slicer-devel] Memory leaks within Python code

Julien Finet julien.finet at kitware.com
Tue Dec 20 20:01:37 EST 2011

When writing Python code, please consider the following issue:
(here is the long discussion associated with it:

Like VTK, Slicer contains some "factory" methods:
 - vtkMRMLScene::CreateNodeByClass()
 - vtkMRMLScene::GetNodesByClass()
 - ...
Like in C++, it means that the functions return an object with a reference
count of 1 that nobody "owns" and the caller must take care of releasing
the object to avoid memory leak.

While there is workaround for some methods (
slicer.mrmlScene.CreateNodeByClass('vtkMRMLModelNode') should be replaced
by slicer.vtkMRMLModelNode() ) there is currently no automatic/clean
mechanism to release the object created by such methods.

The only "hack" that exists for now is to decrease the reference count
manually in your code:
nodes = slicer.mrmlScene.GetNodesByClass('vtkMRMLLinearTransformNode')
nodes.SetReferenceCount(1)      # ----> (was 2, keep 1 for the python

In C++, the following would apply:
vtkCollection* nodes =

or using vtkSmartPointer:
vtkSmartPointer<vtkCollection> nodes;

-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://massmail.spl.harvard.edu/public-archives/slicer-devel/attachments/20111220/9c4f15c1/attachment.html 

More information about the slicer-devel mailing list