The Stack

1 minute read

A stack is a memory arrangement (data structure) for storing and retrieving information (values)

the order of storing values from the stack can be described as LIFO

Stacks are incredibly useful almost every assembley language has special instructions for implementing a stack

in the x86 assembley language there are PUSH and POP instructions

Push and POP operations make use of the stack pointer register ESP which holds the address of the item which is currently on top of the stack

Recall that in x86 architectur, the stack grows dowm in memory.


The PUSH instruction:

  • decrements the address in ESP so that it points to a free space on the stack
  • writes an item to the memory location pointed to by the ESP

ESP stands for extended stack pointer.

Pop instruction

The POP instruction:

  • fetches the item addresssed by the ESP
  • Increments the ESP by the correct amount to removethe item from the stack

Adjusting the stack

Items can be removed rom the stack or space reserved on top of the stack by directly altering the stack pointer: ADD ESP, 8 ; take 8 bytes off the stack SUB ESP, 256 ; Create 256 bytes on stack

ESP always puts it to the top of the stack.

The stack grows downwards so if we have a stack like


And we add an item, X, like so

X | :—: N| Y| Q| K|

So it grows downwards!!


The simplest kind of subroutines perform an identical function each time it runs.

Value paraemters

The information you give to a subroutine is simply a value.

Reference parameters

Consider another subroutine: “given two variables, exchange (swap) their values”. The situation is different here, having only the values of the variables is not enough.

In calling the subroutine we will need to tell it the addresses of the variables.

Such parameters are called reference paraemters.

What you need is not the content but an address, a reference, where it is. Hence the term “pass by reference”.

Calling external subroutines