| |||||||||
In computing, a stack frame is a data structure used to create temporary storage for data and saved state in functions.
Say we wish to implement a function to return a number's square. We could write (in pseudo-assembler)
This methodology does work, but only in very limited circumstances. For example consider if we wish to call square twice?
but on returning how does the function know which return label to return to? We could save the return address somewhere, and jump back to that return address, and this scheme works significantly better, however one problem remains - that all registers are essentially in use and the function could use a register with a useful value in it and thus the caller may be adversely affected.
So, functions store all temporary data in the stack. A special register storing the address of the bottom of the stack (stacks grow downward, that is, smaller addresses - this is a convention) is used and a program stores values in offsets off this stack pointer. When a function is called, the stack pointer moves down to provide enough space to store its temporary variables (other functions called will store values below the new value of the stack pointer). Values stored are often local variables and the return address. When the function returns, the stack pointer is moved back up to save space on the stack.
The stack frame is the collection of local variables and return address and other information stored on the stack.
In "pseudo-assembler" the square function may look something like (where arg is a common argument register, ret is the return value register, and jumpr is an opcode to jump and store the return address in ra)
Note since we use the temporary register a, we store the previous value of a before we use it to prevent overwriting current values already stored in a