The stack is comprised of a number of Stack Frames, with each frame representing a function call.
The size of the stack increases in proportion to the number of functions called, and then shrinks upon return of a completed function.
Works on a LIFO basis.
Each stack frame contains:
- The returning line number
- Any arguments from the called function
- Storage space for all of the function's (automatic) variables
- (various bookkeeping data)
Consider the following program, containing two functions:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
#include <stdio.h> void firstFunc() ; void secondFunc() ; int main() { printf("Hello, World! \n") ; firstFunc() ; return 0 ; } void firstFunc() { int myInt = 17 ; printf("This function has an int with a value of: %d \n", myInt) ; secondFunc() ; printf("See you later."); } void secondFunc() { int yourInt = 42 ; char myChar = 'd' ; printf("This function has an int: %d, and a char: %c \n", yourInt, myChar ) ; } |
- Upon program start an initial stack frame is created for main()
- firstFunc() is called and a new stack frame is created from unused stack memory, containing:
- Line to return to = the line after where it was called from in main() = Line 9
- Storage space for an int
- secondFunc() is called and a new stack frame is created from unused stack memory, containing:
- Line to return to = the line after where it was called from in firstFunc() = Line 15
- Storage space for an int
- Storage space for a char
- When secondFunc() returns, it's frame is used to determine where to return to (line 15 of firstFunc()), then deallocated and the space returned to the stack
- When firstFunc() returns, it's frame is used to determine where to return to (line 9 of main()), then deallocated and the space returned to the stack
When main() returns, the program ends.