C Programming - Stack

Note: Almost all the cases explained below are for intel x86 under linux platform and compiled using gcc.

The stack is LIFO data structure. Stack boundary is defined by extended stack pointer (ESP) register. In over case ESP points to the last address used on the stack, whereas there as architectures in which it points to the first free address.

Suppose we call a function f(1,2,3) from our main program. What happens behind the scenes is as follows.

1. Push the arguments in the reverse order ( eg. 3,2 and 1)

2. Then the function is invoked (CALL), which places the return address into stack, i.e. the current extended instruction pointer register (EIP). This is place where the function should ret when it executes return statement or rather RET opcode.


3. Current value of extended base pointer register (EBP) is pushed into the stack, this is also referred to as stack frame pointer. EBP is used for relative addressing of element in stack. When the calle function returns it is used to refer the elements of the stack of caller function.

4. Once EBP is stored on the stack, we move the current ESP to EBP for refering the elements local to the current stack frame.

5. Reserve the address space required for the local variables of the function.

Labels:


About this entry