Callstack
The Function Call Stack
A basic outline how a function call stack might work operating on the function foo(6, x+1)
- Evaluate function parameters – (x + 1)
- Allocate memory for foo()’s local by pushing a suitable “local block” of memory onto a runtime “call stack”.
- Store the callers current address (“return address”) and switch execution to foo()
- foo() executes with its local block conveniently avaliable at the end of the call stack
- When foo() is finished it exits by popping its locals off the stack and returns to the caller using the previously sorted address. Now the caller’s locals are on the nd of the stack and it can resume executing.
This is why Stack Overflows can occur. Lets say you have a function defined as
void foo() {
int x = 3;
foo();
}
foo will keep getting called, resulting in step 1, 2, 3, but no execution of the methods. The stack will eventually run out of memory
The “local block” is also known as a activation record or a stack frame and can be pushed onto the stack in one CPU operation
In multithreaded environments each thread gets its own call stack instead of just one single global call stack.
Written on September 15, 2017