Stack

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:

  1. The returning line number
  2. Any arguments from the called function
  3. Storage space for all of the function's (automatic) variables
  4. (various bookkeeping data)

Consider the following program, containing two functions:

 

  1. Upon program start an initial stack frame is created for main()
  2.  
     

  3. firstFunc() is called and a new stack frame is created from unused stack memory, containing:
    1. Line to return to = the line after where it was called from in main() = Line 9
    2. Storage space for an int
  4.  

  5. secondFunc() is called and a new stack frame is created from unused stack memory, containing:
    1. Line to return to = the line after where it was called from in firstFunc() = Line 15
    2. Storage space for an int
    3. Storage space for a char
  6.  
     

  7. 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
  8.  
     
     

  9. 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.

 
 

Leave a Reply