Garbage Collection in Python

One of the toughest bug to identify in C is memory leak. It is occurring due to the limitation of garbage collection in C. Only allocation created by ‘malloc’ can be freed. No other allocation can be freed once it has no use. Thus after a few months of working the system may fail due to lack of free memory.

In this case Python is a blessing. There is an automatic garbage collection mechanism in Python. This helps in accumulation of free memory. When an object is deleted the memory is taken by garbage collector and provided for future allocation.

The theory behind it is simple:

When an assignment takes place,


a hold a memory address for the block containing the value 10. That block also hold another value called ‘ref counting’, which stores the number of references to that location. In the first case the value will be 1. When another assignment occurs



the ref counting value becomes 3. Thus to the block containing value 10 there are three references.

What happens when we do


the memory address previously stored in a will get altered. And hence, the ref counting will decrement by one. The interpreter will monitor the ref counting value closely. When the value becomes zero, it means that no one is using that block and nobody can use it in further application, the interpreter will do the garbage collection method, and get back that block of memory as free memory. Now the block can be used with other similar blocks for future allocations. Thus the system will not fail due to the wastage of memory.

But this have a serious trade-off. The Python application are not suited for real time application to great extent. In real time systems, the timings of of operation is of prime importance. When we use Python, during the execution of a real time application the interpretor may go for garbage collection. Thus causing timing issues. Such small timing issues can crash the entire system.


About Odol Shinu

I've completed my B Tech in Information Technology in 2010 from Government Engineering College Sreekrishnapuram Palakkad under Calicut University.

Posted on September 1, 2010, in Python. Bookmark the permalink. 1 Comment.

  1. Well, when you write a = 10, its not right to say that a holds the “address” of 10 – its better to say when a = [10], a is a reference to the list containing 10

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: