1.1k views

In Storage allocation strategies the following strategies are there :

1)Static Allocation

2)Stack Allocation

3)Heap Allocation

What is the difference among all three?

| 1.1k views

A modern computer today works on a combination of all these type of allocation. But While discussing these now We assume that only one of these Storage Allocation strategy is present and see What happens.

Static Allocation: In static allocation, allocation is done at compile time only. For example int var; It is known at compile time that var uses $4B$(or may vary depending on architecture). So, Sizeof DataTypes should be known at Compile time. But In case of Recursion, it is not known at Compile time, that how many time it will be executed.      ( We don't know how many activation records) Thus Recursion is not supported if only Static Allocation is used.

Stack Allocation : Static allocation is done at Run-time. Means a stack is present now. So, Push() and Pop() can be done for function call and function return respectively. So Recursion is Supported, But remember static allocation is not present. So, Variables created are local to each activation record.

Heap Allocation: Now a bunch of memory is present, which can be used at runtime according to our need. So, allocation and deallocation of memory can be done at any time. Means it's your choice to deallocate memory when use of a variable(memory in heap) is over.

by
selected

1. Static Allocation : memory allocated statically (at compile time) and survives the whole program run. i.e., the memory is created as part of the application binary which resides on disk and when a process is created this memory gets mapped on to physical memory, Used for static/global variables and string literals etc. in C.

2. Stack allocation : memory is to be alocated is decided at compile time but is actually created at runtime. For this reason, stack space cannot change dynamically. Used for creating local variables in C. Some platform restrict the stack space for programs, like in Ubuntu, 8MB is the default limit and to use more we have to change the limit using "ulimit -s <newvalue in KB>".

3. Heap allocation: memory is created on heap. Heap can grow dynamically (even stack can grow dynamically, but while stack grows only when functions are called and in units of activation record size), and hence used for dynamic memory allocation like dynamic arrays, malloc etc.

Run a process on linux, get its pid - say 1731. Now doing

cat /proc/1731/maps

gives the memory maps of it.

by