110 likes | 279 Views
The Stack. Keeping Track of Function Calls. 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. Push and Pop. push Decrement SP
E N D
The Stack Keeping Track of Function Calls
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
Push and Pop push • Decrement SP • Write value to new memory location that SP points to pop • Read memory location pointed to by SP • Increment SP
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, #-1 STR R0, R6, #0 POP LDR R0, R6, #0 ADD R6, R6, #+1
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
Stack Setup Example Chosen stack area SP
Stack Operation pop (returns ee) Empty stack push dd push ee SP SP SP SP
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
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?
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