In: Computer Science
What are the major drawbacks of static allocation? How does a hybrid allocation scheme consisting of static allocation, stack-based allocation, and heap based allocation solve the problem
STATIC ALLOCATION
In static memory allocation, the memory required for a program to execute is known beforehand. A fixed amount of memory is allocated to the process due to which a process cannot grow in size even it if needs to. If the exact memory required for execution is not known then the memory needed must be guessed which leads to wastage of memory. As it does not need memory allocation while running, the execution is pretty fast.
HYBRID ALLOCATION
To overcome the above-mentioned problem, a hybrid scheme is used to execute programs. This consists of static allocation, stack-based allocation and heap allocation. Static allocation is done for class-level variables which are shared across the whole program. For example, in Java static variables are shared for all the objects and not created separately for each object.
Stack-based allocation is used for allocating memory to currently executing method's variable. As soon as a method finishes executing, all the respective variable is deleted and the stack frame is popped off the stack. This is done to save memory and engage it only when necessary. Each method/function gets a new stack frame. It must be noted that each Thread has a whole stack of its own.
Heap-based allocation: It is implemented along with stack-based allocation in most of the languages. The idea is that an object is generally very large and cannot be accommodated on the stack and even if it could, it would be very difficult to create and delete such large objects frequently, so this object is stored on heap memory, now what is heap memory? In a layman's language, heap memory is simply the free space available on the RAM. All the objects are created on the heap-memory and referenced from a variable which is stored on the stack. The reference variable holds merely the address of the heap-memory where the object is stored. To manage heap-memory, many algorithms are applied. Java uses MARK AND SWEEP to delete all the dead objects from the heap which cannot be accessed from the stack.