Skip to content
UoL CS Notes

Stack Frames

COMP124 Lectures

Local Variables

Consider a subroutines that contains variable declarations:

int sub1 (int n) {
	int x; float y; char z;
	...
}

The variables x, y, and z are local variables :

  • They only exist while the subroutine is active.
  • Then the subroutines exist, the local variables disappear.

Stack Frames

The a HLL subroutines is called, a new stack frame is created on the stack (by the compiler).

The stack frame holds data pertinent to this particular call, including:

  • Return address
  • Parameters
  • Local Variables

ESP and EBP

Because of nested calls, several stack frames may be present simultaneously.

The ESP always points to the top of the stack; however, this may alter as space is created for local data.

Another register, the EBP (base pointer), remains stable and can be used to a access parameters and variables:

  • Add or subtract offset to EBP.

Stack Frames

Stack grows downwards from the base pointer, with the stack pointer at the end.

The stack frame is made of the following components:

  • Parameters
  • Return addresses
  • The previous base pointer location
  • Local variables

How Does it Work?

  • ESP is always pointing to the top of the stack.
  • EBP initially contains address of base of the stack.

When calling a subroutine to following happens:

  1. The parameters are pushed onto the stack.
  2. The return address is pushed onto the stack.
  3. The old EBP is pushed onto the stack.
  4. The current address of the top of the stack is put onto EBP.
  5. The local variables are installed on the stack, causing the ESP to alter.

When call returns:

  1. Clean up local variables.
  2. Restore previous stack base by popping into EBP.
  3. Pop return address into IP.

Calling routine is responsible for cleaning it’s parameters from the stack.