Tracking down memory leaks?

dmsbox2000-list1@yahoo.com dstark7 at gmail.com
Sun Feb 12 09:01:55 EST 2006


I *think* Python uses reference counting for garbage collection.  I've
heard talk of people wanting to change this (to mark and sweep?).
Anyway, Python stores a counter with each object.  Everytime you make a
reference to an object this counter is increased.  Everytime a pointer
to the object is deleteted or reassigned the counter is decreased.
When the counter reaches zero the object is freed from memory.  A flaw
with this algorithm is that if you create a circular reference the
object will never be freed.  A linked list where the tail points to the
head will have a reference count of 1 for each node, after the head
pointer is deleted.  So the list is never freed.  Make sure you are not
creating a circular reference.  Something like this:

a = [1, 2, 3, 4, 5, 6]
b = ['a', 'b', 'c', 'd']
c = [10, 20, 30, 40]

a[3] = b
b[1] = c
c[0] = a

the last assignment creates a circular refence, and until it is
removed, non of these objects will be removed from memory.

I'm not an expert on python internals, and it is possible that they
have a way of checking for cases like this.   I think the deepcopy
method catches this, but I don't *think* basic garbage collection look
for this sort of thing.

David




More information about the Python-list mailing list