Memory leak while looping

logistix logistix at cathoderaymission.net
Thu Apr 17 01:28:43 EDT 2003


> -----Original Message-----
> From: python-list-admin at python.org 
> [mailto:python-list-admin at python.org] On Behalf Of Roger Hancock
> Sent: Thursday, April 17, 2003 1:00 AM
> To: python-list at python.org
> Subject: Memory leak while looping
> 
> 
> I'm just starting to play with writing C extensions for 
> Python.  In the process of doing so, I called one of my 
> extension functions thousands of times only to discover that 
> a leak was eating up all the memory in my system.  Upon 
> further investigation, I found I could produce the same 
> result with the following python code with my extension 
> completely out of the picture:
> 
> #!/usr/bin/env python2
> 
> for i in range(1,10000000):
>     item = i
> 
> 
> I would have thought that the memory for "item" would be 
> freed as new "item"s were created.  However, this doesn't 
> seem to be the case.  I would appreciate any clarification on 
> this issue.
> 
> 

The range function returns a list.  So in this case you're creating a
list of 10 million items before you even enter the body of the for loop.
Try using xrange() instead.  This is an iterator so it doesn't need to
create an entire list in memory.

Were you calling range() in your extension code or doing something else?






More information about the Python-list mailing list