DYSTOPIANPIXEL

Understanding the stack

Learn last-in, first-out storage and stack balance.

Next Asset Lab concept artwork showing sprite patterns, palette colours and animation frames
Next Asset Lab concept artwork · Begin with Odin Dev.2k and the foundations of Z80 assembly.
TUTORIAL 2 / PART 10

The stack: memory used in last-in, first-out order

The stack is not another special bank of CPU registers. It is an area of ordinary addressable memory used according to a strict convention. The 16-bit SP register — the Stack Pointer — identifies the current top of the stack.

A useful image is a stack of plates. Put a plate on the top and it is the first one you remove. This is called last in, first out, or LIFO. CPU return addresses and temporarily saved register pairs can use the stack.

On a Z80, the stack usually grows towards lower addresses as values are pushed: storing a 16-bit value on the stack reduces SP by two. Retrieving it increases SP by two. That is why both halves of a 16-bit address can be stored and recovered.

A schematic example — not your Odin SP value

Suppose, just for illustration, that SP initially held $D000. If a CALL needed to save the two-byte return address $6005, the resulting bytes would look like this:

Before saving: SP = $D000

After saving: SP = $CFFE

address $CFFE contains $05 (low byte)

address $CFFF contains $60 (high byte)

On RET: PC receives $6005

SP returns to $D000

The addresses above are invented to explain the mechanism. They are not instructions for selecting a stack address on the Spectrum Next. Odin, NextZXOS and any eventual NEX application have their own memory arrangements. We are not going to set SP manually inside an Odin test.

Why an unbalanced stack is serious

If a subroutine accidentally removes one saved value too many, the bytes now on top may no longer be a valid return address. Then RET can jump to unintended memory. This is not merely a wrong result: it can crash the programme or leave the computer unresponsive. The safe rule is simple: every path through a routine must leave the stack in the same state in which it was found, except for the expected CALL/RET mechanics.