Memory management and the Stack
The OS allocates memory for each process or program for data and code. The memory allocated for each process consists of many parts: the stack holds local variables, the heap holds dynamic memory, the data segment holds global variables, and finally the code segment which holds the code is and read only. Memory management depends on the hardware and the operating system.
A stack organizes a set of data elements in a Last In, First Out ( LIFO ) manner. The three basic operations on a stack are: push which adds a new element to the top of the stack, pop which removes an element from the top of the stack, and a check to see if the stack is empty.
The stack consists of stack frames. There is one for each function. It gets allocated when a function is called and de-allocated when it returns. The stack pointer points to the last element on the stack. Each stack frame provides memory for arguments, return values and local variables. There is also a frame pointer which provides a starting point to the local variables using offsets.
When a function is called, a new stack frame is created. Arguments are stored in the stack frame. Current frame pointer and return address are recorded in the stack frame. Memory for local variables are allocated. And finally, the stack pointer is adjusted. When a function returns, the top stack frame gets removed, old frame pointer and return address gets restored and the stack pointer gets adjusted.