Reading Note: Stack and Heap of the Process

2022-04-10•softwareoperating-system

The Process

A program can do nothing unless its instructions are executed by a CPU. A program in execution is a process.

The status of the current activity of a process is represented by the value of the program counter and the contents of the processor’s registers.

layout-of-a-process-in-memory

Layout of a process in memory

The size of text and data sections are fixed. Their size does not change during the program run time.

The stack and heap sections shrink and grow dynamically during program execution.

Stack

A stack is a simple last-in, first-out (LIFO) data structure.

The structure of the stacks is rigid and they only allow access at the top level. But this rigid also makes the stacks easy to implement. The push and pop operations are fast and efficient.

The stacks are used for function calls. Each time a function is called, the parameters, local variables, and the return address are pushed onto the stack. Returning from the function call pops those items off the stack. The variables that are declared and initialized before runtime are stored in the stack.

Heap

The heap is more flexible than the stack. The stack only allows allocation and deallocation at the top. The heap allows the program to allocate or deallocate the memory anywhere in a heap.

So, the advantage is that the program can store the data on the heap in any order.

The disadvantages are:

The heap is used for memory that is dynamically allocated during program run time. All the variables created or initialized at runtime are stored in the heap.

layout-of-a-c-program-in-memory

Layout of a C program in memory

References