Get new post automatically.

Enter your email address:


3.3.1 Stack Frames

Almost invariably, programs compiled from modern high level languages (even C!) make use of a stack frame for the working memory of each procedure or function invocation. When any procedure or function is called, a number of words - the stack frame - is pushed onto a program stack. When the procedure or function returns, this frame of data is popped off the stack.
As a function calls another function, first its arguments, then the return address and finally space for local variables is pushed onto the stack. Since each function runs in its own "environment" or context, it becomes possible for a function to call itself - a technique known as recursion. This capability is extremely useful and extensively used - because many problems are elegantly specified or solved in a recursive way.
Program stack after executing a pair of mutually recursive functions:
function f(int x, int y) {
    int a;
    if ( term_cond ) return ...;
    a = .....;
    return g(a);
    }

function g(int z) {
    int p,q;
    p = ...; q = ...;
    return f(p,q);
    }
Note how all of function f and g's environment (their parameters and local variables) are found in the stack frame. When f is called a second time from g, a new frame for the second invocation of f is created.

Key terms

push, pop
Generic terms for adding something to, or removing something from a stack
context
The environment in which a function executes: includes argument values, local variables and global variables. All the context except the global variables is stored in a stack frame.
stack frames
The data structure containing all the data (arguments, local variables, return address, etc) needed each time a procedure or function is called.