Memory life cycle
The memory life cycle for every programming language is pretty much similar. It works in the following manner:
Let's see the following example, which explains the memory allocation for different types of variables and objects:
Reading and Writing Values
Releasing of a Memory When It is not in use
When it's time to release the allocated memory, most of the memory management issues occur at this phase. The most complicated task at this stage is to determine when the specific variable, object, or function will no longer be in need.
Low-level programming languages ask the developer to manually specify at which point they want to release the memory of an allocated instance.
The main usage of a garbage collection is to automatically monitor and find when a specific block will not be in use and reclaim it.
Reference-counting garbage collection
Let's understand it with the below example:
Limitations (Circular References)
From the above example, we have created two objects having references to one another, forming a reference cycle; this situation is called circular references. When the function myFunction() completes its execution, it will go out of scope. They will not be in need at that point, but their allocated memory will be reclaimed. Thus, the garbage collector will not clean their allocations.
However, the garbage collector reference counting algorithm will not recognise them as a reclaimable objects, but each of them has a reference; that's why neither of them will be marked for garbage collection. The circular references problems are one of the reasons for the memory leaks in an application.
IE 6 and IE 7 maintain the reference counting garbage collectors, but no other modern engine uses reference counting garbage collectors to prevent memory leaks due to circular references.
The mark-and-sweep algorithm reduces the usage of the "an object is no longer used" algorithm; instead, it focuses on the "an object is unreachable" approach.
This algorithm is an improvement of the reference-counting algorithm. It will consider an object having zero references as unreachable. So, in this algorithm, the object does not hold true if it has a circular reference.
In the first example, there were no two objects referencing any resource after the function call. Thus, they will be considered unreachable by the garbage collector, and their memory can be reclaimed.
There may be a time in the application when it will be convenient to manual specify what memory will be released. To release the memory of an object, we need to make it explicitly unreachable manually.