The stack

The stack is a range of memory addresses that can be used for temporary storage of data from either within a procedure or as the normal method of passing parameters to a procedure.

The stack is normally accessed in code by the mnemonics PUSH and POP.  The stack is accessed on a last on, first off basis which means that the last value pushed onto the stack is the first one to be popped back off the stack.

The next position that can be written on the stack is called the top of the stack.  When a piece of data is pushed onto the stack, the processor decrements the stack pointer ESP then writes the data to the top of the stack.  When a piece of data is popped back off the stack, the processor reads the data from the top of the stack then increments the stack pointer.  Therefore, the stack address decreases as more data is pushed onto it, and the address increases as data is popped back off the stack.

In the following images, each square represents 1 byte on the stack, and the different colors are intended to demonstrate the different data sizes being pushed and popped.  The top of the stack is the left side of each image.

The following sequence demonstrates the stack layout as one 32-bit and two 16-bit values are pushed and popped from the stack.

Existing stack layout:


Push a 32 bit value (PUSH EAX)

Push a 16 bit value (PUSH CX)

Push another 16 bit value (PUSH DX)


Pop a 16 bit value (POP DX)

Pop second 16 bit value (POP CX)

Pop the 32-bit value (POP EAX)

If you wrote the following code:

! MOV EDX, 100

! MOV ECX, 500


' push the 2 values onto the stack

! PUSH EDX  ; EDX has the value 100

! PUSH ECX  ; ECX has the value 500


' pop the 2 values off the stack

! POP EAX   ; EAX has the value 500

! POP ECX   ; ECX has the value 100


PowerBASIC conforms to the 32-bit Windows convention that specifies that certain registers must be preserved around blocks of assembly code, namely EBX, ESI, and EDI.  While EAX, ECX, and EDX can be modified freely within a procedure, some conditions apply to their use too.  See Saving registers for more detailed information.


See Also

The Inline Assembler

Balancing the stack

Tricks of the stack

Stack Overhead Reduction

Saving registers

Saving Registers at the Sub/Function level