I'm trying to understand how the stack works when something is pushed and pulled from it, sorry if the question sounds very simple.
I want to start with something super basic, like an 8 bit memory (I know it will be an oversimplification, but let's start simple)
The way I would design a stack is the following:
SP will initially point to the highest position in memory: 0xFF
0xFF: <- SP
When a push command is issued, I would save val in the position pointed by SP and then decrease SP.
0xFE: <- SP
0xFF: val
A pop command will first increment SP and then move the value pointed by SP into a register.
Basically my SP points to the first available position in the stack.
However it appears that this is not how it's implemented in real systems.
Looking at the assembly manual for the push instruction:
Decrements the stack pointer and then stores the source operand on the top of the stack.
So basically SP points to the latest stored value.
My question is: By first decreasing the stack pointer, isn't the very top of the stack unusable? How can we store data to the first position of the stack if we first decrease the pointer before saving the data?
Is there a reason to design the stack pointer this way?
1or larger from SP. Doing decrement-then-store, indexes into the valid stack values start at0, just like conventional access for any type of array/pointer-based storage. IMHO that's a useful consistency. It also means you're not "wasting" offsets, i.e. the offset of0actually is meaningful instead of never useful. - Peter Dunihopushinstruction, where you have to manually decrement the stack. But if you do have a push instruction, the store-and-decrement would be atomic WRT. interrupts. (Interrupts always logically happen at instruction boundaries; partial progress is discarded or the interrupt waits for the instruction to complete.) I've never heard of an ISA where simple instructions likepushwere interruptible with half the instruction completed. So full vs. empty stack is mostly an arbitrary design choice, but having SP pointing at data can be useful. - Peter Cordespushinstruction, one can use a sp--/store pair of instructions to push on the stack and this needs to be protected from interrupts by first decrementing sp. And, while it is not strictly required technically, it makes sense to have exactly the same mechanism with a push or a pair of instructions. - Alain Merigot