7 - Stack Management
7 - Stack Management
Low Address
Chapter 3: Stack Management & Procedures CCSE YANBU 5
Stack Instructions
Two basic stack instructions:
PUSH source
POP destination
Source can be
General-purpose register
Segment register: CS, DS, SS, ES
Memory operand (memory-to-stack transfer is allowed)
Destination can be
General-purpose register
Segment register, except that “POP CS” is NOT allowed
Memory operand (stack-to-memory transfer is allowed)
MOV AX,86
PUSH AX
MOV AX,70 SP 45 300
PUSH AX SP 86 298
SP 70 296
SP 298
300
296
Chapter 3: Stack Management & Procedures CCSE YANBU 7
Examples on the Push Instruction
• Suppose we execute: The stack grows
– PUSH AX ; AX = 80FFh downwards
– PUSH BX ; BX = 2Eh The area below SP is
free
– PUSH CX ; CX = B61Dh
BEFORE AFTER
2FFB4 SP 2FFB4
2FFAD 2FFAD
POP AX
POP BX
SP 45 300
AX 70
SP 86 298
BX 86 SP 70 296
SP 298
300
296
Chapter 3: Stack Management & Procedures CCSE YANBU 9
Examples on the Pop Instruction
BEFORE AFTER
2FFB4 2FFB4
2FFAD 2FFAD
Stack growth
Code growth SP
CS IP
0000
0100
SP IP
Stack growth Code growth
SS SP ES SS DS CS IP
0000 0000
Chapter 3: Stack Management & Procedures CCSE YANBU 11
Uses of the Runtime Stack
Runtime Stack can be utilized for
Temporary storage of data and registers
Transfer of program control in procedures and interrupts
Parameter passing during a procedure call
Allocating local variables used inside procedures
PUSH BX
POP AX
PUSH BX ; save BX
PUSH CX ; save CX
. . .
MOV BX,adr ; BX and CX can now be modified
ADD CX,[Bx]
. . .
POP CX ; restore CX first, then
POP BX ; restore BX
Chapter 3: Stack Management & Procedures CCSE YANBU 13
Example: Nested Loop
When writing a nested loop, push the outer loop counter CX before
entering the inner loop, and restore CX after exiting the inner loop
and before repeating the outer loop
. . . ; outer loop
POP CX ; restore outer loop count
LOOP L1 ; repeat the outer loop