Upload
prosper-henderson
View
212
Download
0
Embed Size (px)
Citation preview
The StackKeeping Track of Function Calls
2
The Stack Pointer
• The CPU usually contains a special register, called the Stack Pointer (SP)
• It is used by the CPU whenever it needs to push something onto, or pop something off, the stack
3
Push and Pop
push
1. Decrement SP
2. Write value to new memory location that SP points to
pop
1. Read memory location pointed to by SP
2. Increment SP
4
Or in reverse…
Some CPUs reverse steps 1 and 2 so that:
• push write then decrement
• pop increment then read
On LC-3
• PUSH ADD R6, R6, #-1STR R0, R6, #0
POP LDR R0, R6, #0
ADD R6, R6, #+1
5
6
Setting up the Stack
• The CPU assumes that the SP is pointing to an area of memory that has been reserved for stack use
• It is therefore necessary for the programmer to choose where to put the stack, and to initialise the SP to the appropriate address before using it!
• For a decrement-before-write CPU, the appropriate address is one higher than the highest address in the reserved area
7
Stack Setup Example
0FF
100
1FE
1FF
200
Chosen stack area
SP
8
Stack Operation
zz
yy
xx
ww SP
zz
yy
dd
ww
zz
ee
dd
ww
zz
ee
dd
ww
SPSP
SP
Empty stack push eepush ddpop
(returns ee)
9
Stack Overflow
• If you push more data onto the stack than will fit into the area you’ve allocated to it, then you have created a stack overflow
• This is potentially disastrous, since you may overwrite (and thus destroy) important data, or instructions, outside the stack area
10
Stack Overflow
• Advanced computers have special software to detect stack overflow, but simple ones do not
• On a simple computer, you have to design the program to avoid it
• Now you know what the ‘stack overflow’ error message you may have seen means
• What might be a common cause?
11
Test Yourself!
• What is meant by Stack Overflow?
• What is the Stack Pointer (SP) used for?
• Explain push and pop with regards to the stack