Can a C compiler rearrange stack variables?

前端 未结 11 2190
孤街浪徒
孤街浪徒 2020-12-09 11:07

I have worked on projects for embedded systems in the past where we have rearranged the order of declaration of stack variables to decrease the size of the resulting executa

11条回答
  •  时光说笑
    2020-12-09 11:13

    As there is nothing in the standard prohibiting that for C or C++ compilers, yes, the compiler can do that.

    It is different for aggregates (i.e. structs), where the relative order must be maintained, but still the compiler may insert pad bytes to achieve preferable alignment.

    IIRC newer MSVC compilers use that freedom in their fight against buffer overflows of locals.

    As a side note, in C++, the order of destruction must be reverse order of declaration, even if the compiler reorders the memory layout.

    (I can't quote chapter and verse, though, this is from memory.)

提交回复
热议问题