How to debug memory leaks in scripted modules

Hello everyone, I have been writing a Python scripted module for slicer, and recently I have been getting warnings about memory leaks when I go to close slicer, is there a recommended way of diagnosing where those are coming from in my code?


It can be a bit of a bear of a task, but generally there seem to be some pretty common method usages that cause the memory leaks.

I would guess it is because you are using some methods like GetNodesByClass rather than something like GetNthNodeByClass.

for i in range(slicer.mrmlScene.GetNumberOfNodesByClass('vtkMRMLSegmentationNode')):
            segmentation_node = slicer.mrmlScene.GetNthNodeByClass(i, 'vtkMRMLSegmentationNode')

Also things like CreateNodeByClass can cause memory leaks, but can be avoided by using AddNewNodeByClass instead.

See Documentation/Nightly/Developers/Tutorials/MemoryManagement - Slicer Wiki for more details.

Also related is Memory leaks when returning vtkCollection objects to Python as return value · Issue #2718 · Slicer/Slicer · GitHub.


Thank you so much! That looks like what is probably going on in my code, thank you for the information!