Explain the concept of a stack frame in a nutshell

ikostia picture ikostia · Apr 7, 2012 · Viewed 114.7k times · Source

It seems that I get the idea of call stack in programming language design. But I cannot find (probably, I just don't search hard enough) any decent explanation of what stack frame is.

So I would like to ask someone to explain it to me in a few words.

Answer

Tony R picture Tony R · Apr 7, 2012

A stack frame is a frame of data that gets pushed onto the stack. In the case of a call stack, a stack frame would represent a function call and its argument data.

If I remember correctly, the function return address is pushed onto the stack first, then the arguments and space for local variables. Together, they make the "frame," although this is likely architecture-dependent. The processor knows how many bytes are in each frame and moves the stack pointer accordingly as frames are pushed and popped off the stack.

EDIT:

There is a big difference between higher-level call stacks and the processor's call stack.

When we talk about a processor's call stack, we are talking about working with addresses and values at the byte/word level in assembly or machine code. There are "call stacks" when talking about higher-level languages, but they are a debugging/runtime tool managed by the runtime environment so that you can log what went wrong with your program (at a high level). At this level, things like line numbers and method and class names are often known. By the time the processor gets the code, it has absolutely no concept of these things.