Search code examples
c++variablescompiler-constructionstackstatic-memory-allocation

Stack memory allocation of variables in c++


How does the c++ compiler organize the variables that are initialized in a function to store them so the computer will find them the fastest way?

I understand that the compiler puts them one after an other on the stack but there has to be some logic behind it, I was searching Google for hours on end but I could not find anything.

For example:

int main()
{
    float a;
    int b;
    char c;
    double d;
}

This should occupy more memory than the one below because of the way the c++ compiler is storing in the memory.

The exact bits used are the same, of course, but they should be stored in a more efficient order in the example below. Where in memory would these variables be stored by the compiler in the next example? As far as I understood a variable is always stored on a block such that (logical number) % (number of bytes the datatype) = 0

int main()
{
    char c;
    int b;
    float a;
    double d;
}

Solution

  • This should occupy more memory than the one below because of the way the c++ compiler is storing in the memory.

    Not really, the stack memory consumed by both functions should be the same for any sane optimizing compiler... Modern C++ Compilers are really aggressive at certain optimizations.

    Other than suitable alignments, C++ does not impose memory address ordering for automatic variables in functions. While that is true, the observable behavior of the program must not be changed by the compiler.

    I guess you are trying to talk about structs and classes where the memory layout and address ordering of variables are as declared.

    How does the c++ compiler organize the variables that are initialized in a function to store them so the computer will find them the fastest way?

    In practice, every access to an automatic variable in C++ is a simple pointer offset with respect to the stack pointer1 (except variables the compiler placed directly in a register). Additionally, to speed things up to such automatic variables (in no order):

    • The Compiler eliminates dead variables

    • The compiler will find the best order to store each of them to meet suitable alignment

    • The compiler may use the CPU register directly depending on what it's Register Allocation algorithm decides

    • The compiler may lump certain variables together into a vector register and use vector instructions provided it will yield correct results.

    • ...and so much more.


    1: Even the stack pointer is aligned by most compilers.