In C language, developers manually allocate or deallocate memory with malloc(), calloc(), realloc() and free() methods.
- Allocation of Memory
- Utilization of Memory
- Releasing Memory
In these examples, variable1 allocated memory for a number whereas the string is allocated in the memory of variable2 as shown below.
var variable2 = "Memory Allocation";
If you want to assign memory for numerous objects then use the following code.
Array allocated in the memory of variable6 as shown below.
You can also allocate memory for distinct methods. Here is the code to allocate memory for a method.
return x + 20;
The process of memory allocating and releasing the memory when not required is known as garbage collection. Algorithms are used to find out which memory is irrelevant for the tasks. This section explicitly deals with the main algorithms used in garbage collection and their limitations.
Reference counting garbage collection algorithm
Reference counting garbage collection algorithms are viewed as the great fundamental sort of garbage collection. This algorithm not only decides if any resource is significant or not, it also filters the memory to decide whether an item has some other instances referring to it. An instance that has null references is accounted for as garbage.
Mark & sweep algorithm
A garbage collector helps to free up memory whenever an instance is inaccessible, instead of a zero referring to an object. Initially, the garbage collector searches all global or root instances along with their object references. Through this algorithm, the collector will distinguish between the reachable and inaccessible instances. Subsequently, inaccessible instances will be collected automatically by the garbage collector.