Stack Frames

A stack frame is a memory management technique used in some programming languages for generating and eliminating temporary variables. In other words, it can be considered the collection of all information on the stack pertaining to a subprogram call. Stack frames only exist during the runtime process.

All this makes clear that there must be a way for the program in execution to ‘remember’ the return address each time the execution flow enters a function and of course each function needs to have its own memory area where it can store all of the above (return address, local variables, etc.)

Every time we enter a function, a stack frame for this function is created through the function prologue. A function prologue is a set of instructions for which the purpose is to allocate the necessary memory area for that specific function inside the stack, and itis the first thing done every time we enter a function. Very often, immediately after the function prologue we notice that some of the general-purpose registers are pushed onto the stack. This happens because we might want to use these registers during the execution of the function, but we will | still need their initial values once this function is completed,§ so its stack frame is used as a temporary storage area.

However, keep in mind that the memory size allocated by the OS for the stack, used by the thread under execution, is fixed. This means that we cannot just keep pushing values on it indefinitely, and this is also one of the reasons why we always clean up the stack at the end of a function. Also, once the function is complete, we need to re-balance the stack; in other words, ‘free’ the memory allocated for this stack frame and restore the values of ESP and EBP registers.

This is done by the function epilogue, which is, again, a set of instructions that we'll see in a while.

In case the initial values of other general-purpose registers were saved after the function prologue, then these have to be popped out of the stack into their respective registers before the function epilogue occurs.

Remember, last-in-first-out.

Function Prologue/Epilogue Example
Current State of the stack before the execution of the function prologue

Now we will see how the stack frame, demonstrates the state of the stack after the execution of every instruction.

PUSH EBP
MOV EBP,ESP
SUB ESP, 10h

Last updated