Stacks and Heaps CS-502 Fall 2007 1 A Short Digression Stacks and Heaps CS-502, Operating Systems Fall 2007 (Slides include materials from Operating System Concepts, 7 th ed., by Silbershatz, Galvin, & Gagne and from Modern Operating Systems, 2 nd ed., by Tanenbaum)
21
Embed
Stacks and HeapsCS-502 Fall 20071 A Short Digression Stacks and Heaps CS-502, Operating Systems Fall 2007 (Slides include materials from Operating System.
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Stacks and HeapsCS-502 Fall 2007 1
A Short DigressionStacks and Heaps
CS-502, Operating SystemsFall 2007
(Slides include materials from Operating System Concepts, 7th ed., by Silbershatz, Galvin, & Gagne and from Modern Operating Systems, 2nd ed., by Tanenbaum)
Stacks and HeapsCS-502 Fall 2007 2
Digression: the “Stack”
• Imagine the following program:–int factorial(int n){
if (n <= 1)
return (1);
else
int y = factorial(n-1);
return (y * n);
}
• Imagine also the caller:–int x = factorial(100);
• What does compiled code look like?
Stacks and HeapsCS-502 Fall 2007 3
Compiled code: the caller
int x = factorial(100);
• Put the value “100” somewhere that factorial can find
• Put the current program counter somewhere so that factorial can return to the right place in caller
• Provide a place to put the result, so that caller can find it
Stacks and HeapsCS-502 Fall 2007 4
Compiled code: factorial function
• Save the caller’s registers somewhere• Get the argument n from the agreed-upon place• Set aside some memory for local variables and
intermediate results – i.e., y, n - 1
• Do whatever it was programmed to do
• Put the result where the caller can find it• Restore the caller’s registers• Transfer back to the program counter saved by the
caller
Stacks and HeapsCS-502 Fall 2007 5
Question: Where is “somewhere”?
• So that caller can provide as many arguments as needed (within reason)?
• So that called routine can decide at run-time how much temporary space is needed?
• So that called routine can call any other routine, potentially recursively?
Stacks and HeapsCS-502 Fall 2007 6
Answer: a “Stack”
• Stack – a linear data structure in which items are added and removed in last-in, first-out order.