Home > other >  Addressing stack variables
Addressing stack variables

Time:10-07

As far as I understand, stack variables are stored using an absolute offset to the stack frame pointer. But how are those variables addressed later? Consider the following code:

#include <iostream>
int main()
{
    int a = 0;
    int b = 1;
    int c = 2;
    std::cout << b << std::endl;
}

How does the compiler know where to find b? Does it store its offset to the stack frame pointer? And if so, where is this information stored? And does that mean that int needs more than 4 bytes to be stored?

CodePudding user response:

The location of stack variables is a compile-time constant. The compiler always knows how many things it's pushed to the stack since the beginning of the function and therefore the relative position of any one of them within the stack frame.

On x86 this is usually achieved by addressing relative to the ebp or esp registers, which are typically used to represent the "beginning" and "end" of the stack frame. The offsets themselves don't need to be stored anywhere as they are built into the instruction as part of the addressing scheme.

Note that local variables are not always stored on the stack.
The compiler is free to put them wherever it wants, so long as it behaves as if it were allocated on the stack.
In particular, small objects like integers may simply stay in a register for the full duration of their lifespans (or until the compiler is forced to spill them onto the stack), constants may be stored in read-only memory, or any other optimization that the compiler deems fit.

  • Related