Memory and the stack

Writing single bytes into the data section, then making room on the stack by moving esp.

What you'll learn
  • Read and write memory with [address + offset] operands and size hints
  • Explain why the stack grows towards lower addresses
  • Allocate stack space by subtracting from esp

Registers are few. Everything else lives in memory, addressed by number. Square brackets mean “the memory at this address”:

section .data
    addr db "yellow"

section .text
_start:
    mov [addr], byte 'H'        ; first byte
    mov [addr+5], byte '!'      ; sixth byte
    ; ... sys_write(1, addr, 6) prints "Hello!"

05_memory_access.asm turns yellow into Hello! by overwriting two bytes in place. The byte keyword matters: mov [addr], 'H' alone is ambiguous — the assembler cannot tell whether to write 1, 2 or 4 bytes — so the size must be stated on one side.

05_memory_access.asm. The green row is the .data section; two byte writes change 'yellow' into 'Hello!' before it is printed.

The stack

Every program also gets a stack: a region of memory whose current top is held in esp. On x86 it grows downwards, towards lower addresses. Making room is a subtraction:

_start:
    sub esp, 4
    mov [esp], byte 'H'
    mov [esp+1], byte 'e'
    mov [esp+2], byte 'y'
    mov [esp+3], byte '!'
    ; ... sys_write(1, esp, 4) prints "Hey!"

After sub esp, 4, the four bytes from esp to esp+3 belong to the program. Filling them and passing esp as the buffer address prints Hey!. Nothing is “allocated” in any formal sense — the stack pointer simply moved, and the space above it is now considered in use.

06_stack.asm. Each stack row is four bytes, high addresses at the top. sub esp, 4 moves the orange esp marker down one row; the byte writes fill the new slot from its low address up.

Why downwards? Historically, a program’s code and data sat at low addresses and grew up, while the stack started at the top and grew down; the two could share one free gap without either needing a fixed size. The convention stuck.

Try it yourself. Change 06_stack.asm to store "Hey!" with a single mov dword [esp], 0x21796548 instead of four byte moves. Why are the bytes written in that order? (Hint: x86 is little-endian, and the stepper’s stack rows show it.) Then try writing to msg in 02_hello_world.asm after moving it into section .text — what happens, and why?

View source on GitHub →