# How to debug memory leaks in scripted modules

**URL:** <https://discourse.slicer.org/t/how-to-debug-memory-leaks-in-scripted-modules/20629>\
**Category:** Development\
**Created:** [November 15, 2021, 9:30pm UTC](https://discourse.slicer.org/t/how-to-debug-memory-leaks-in-scripted-modules/20629 "2021-11-15T21:30:46Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![tsims](https://sea2.discourse-cdn.com/flex002/user_avatar/discourse.slicer.org/tsims/32/11853_2.png) [@tsims](https://discourse.slicer.org/u/tsims)\
**Post date:** [November 15, 2021, 9:30pm UTC](https://discourse.slicer.org/t/how-to-debug-memory-leaks-in-scripted-modules/20629/1 "2021-11-15T21:30:46Z")

</div>

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?

Thanks!

---

<div class="post-metadata">

**Author:** ![jamesobutler](https://sea2.discourse-cdn.com/flex002/user_avatar/discourse.slicer.org/jamesobutler/32/7511_2.png) [@jamesobutler](https://discourse.slicer.org/u/jamesobutler)\
**Post date:** [November 15, 2021, 11:15pm UTC](https://discourse.slicer.org/t/how-to-debug-memory-leaks-in-scripted-modules/20629/2 "2021-11-15T23:15:33Z")

</div>

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`.

```python
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](https://www.slicer.org/wiki/Documentation/Nightly/Developers/Tutorials/MemoryManagement#Python_scripts_and_scripted_modules) for more details.

Also related is [Memory leaks when returning vtkCollection objects to Python as return value · Issue #2718 · Slicer/Slicer · GitHub](https://github.com/Slicer/Slicer/issues/2718).

---

<div class="post-metadata">

**Author:** ![tsims](https://sea2.discourse-cdn.com/flex002/user_avatar/discourse.slicer.org/tsims/32/11853_2.png) [@tsims](https://discourse.slicer.org/u/tsims)\
**Post date:** [November 16, 2021, 2:44pm UTC](https://discourse.slicer.org/t/how-to-debug-memory-leaks-in-scripted-modules/20629/3 "2021-11-16T14:44:24Z")

</div>

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