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.