The call stack and stack frames

Cards (8)

  • When a subroutine is called, an entry is placed on the call stack.
  • When a subroutine is called from another subroutine (the caller), several things must happen:
    • The parameter values must be passed from the caller to the called subroutine
    • The state of the caller must be saved before program control is switched to the called subroutine
    • The called subroutine must be executed
    • Return value(s) from the called subroutine must be passed back to the caller
    • The state of the caller must be reinstated so that it can finish executing at the point immediately following the position that the subroutine call was made
  • A call stack is an area of memory that is allocated to a program to store information about each active subroutine. An active subroutine is one that has been called, but has not yet finished execution. At any point during a program's execution, there may be multiple active subroutines.
  • The call stack, like any stack, is finite in size. Memory space is allocated for the call stack before the program is run. In some low-level languages, the amount of memory allocated is determined by the programmer. In high-level languages, it is controlled by the program language variables, the compiler, and/or the operating system.
  • If you write a subroutine that calls itself with no means of escape, you will fill up the stack with hundreds of stack frames, leading to stack overflow.
  • When a subroutine is called, a stack frame is created with memory space allocation for:
    • The values of any local variables
    • The values of any parameters
    It also holds a reference to the 'execution point' of the subroutine; think of this as the line number where program control needs to return to if another subroutine is called. Sometimes this is called the return pointer.
  • When you code a return statement, you are instructing the translator that, at this point, the subroutine should terminate and return a value. Once a return statement is run, no more lines of that subroutine will be executed and the stack frame for that subroutine will be removed from the call stack.
  • When a program has finished running, the memory allocated to the call stack is made available again.