Call stack
In computer science, a function stack (or call stack) is a special stack which stores information about the functions/subroutines in a computer program which are currently being executed. It is a stack because when one function calls another, rather than simply jumping to another part of the program, the current address in the caller function is pushed onto the stack. Its value is then used when the callee function terminates, by popping the callee function's information off the stack and jumping the program counter back to the value that was stored there.
In high-level programming languages, the specifics of the function stack are usually hidden from the programmer. They are given access only to the list of functions, and not the memory on the stack itself. Assembly languages on the other hand, require programmers to be involved with manipulating the stack. The actual details of the stack in high-level languages depend upon the compiler, and which instruction set the program is being compiled for.
Assembly languages usually store some other information on the stack as well, such as parameters which are passed into the callee, and local variables of the callee. An example of the information placed on the stack follows (for a case where function1 calls function2):
- previous stack data
- function1 local variables
- parameters for function2
- function1 return address (of the instruction which called function2)
- function2 local variables
(From Subroutine)
Some assembly languages may store local variables and parameters on a separate stack to the return addresses.
The fact that local variables are stored on the stack provides languages with the ability to implement recursive functions. If local variables were stored in some other place, then when a function called itself, the two instances of the function in memory would share the same local variables, and therefore the callee would corrupt the local variables in the caller.
By having each instance of the function's local variables in a separate frame on the stack, the local variables in recursive functions do not interfere with one another.