Search code examples
x86stack-memorystack-pointer

How does the stack pointer register work


Well, how does the stack work? For example the instruction:

push ax

is equal to:

sub sp, 4
mov sp, ax

where sp is a stack pointer. Is that right?

My question is - what's the point of subtracting 4 from the sp register if a moment later I change it to the whole different value?


Solution

  • I think that's supposed to read

    sub  sp, 2       ; AX is only 2 bytes wide, not 4
    mov [sp], ax     ; store to memory, not writing the register
    

    That is, put the value of ax into the memory pointed to by sp.

    Perhaps your sub sp, 4 came from pushing a 32-bit register? The stack pointer always decreases by the push operand-size.

    (Note that push doesn't modify FLAGS, unlike sub. This pseudocode / equivalent isn't exactly equivalent, also not for the push sp case. See Intel's manual, or this Q&A for pseudocode that works even in those cases.)