gcc如何将局部变量压入堆栈? [英] How does gcc push local variables on to the stack?

查看:99
本文介绍了gcc如何将局部变量压入堆栈?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  voidF(){int a [1];int b;int c;int d [1];} 

我发现,对于此示例,这些局部变量未按顺序压入堆栈.b和c按照其声明的顺序进行推送,但是a和d组合在一起.因此,编译器分配数组的方式与其他任何内置类型或对象不同.

这是C/C ++要求还是gcc实现细节?

解决方案

C标准没有说明局部变量的分配顺序.它甚至不使用堆栈"一词.它仅要求局部变量具有一个 lifetime ,该生命周期从进入最接近的封闭块开始(基本上是在执行到达 {时),然后从该块退出(到达} ),并且每个对象都有唯一的地址.它确实承认两个不相关的变量可能恰好在内存中相邻(由于涉及指针算术的模糊技术原因),但没有说明何时可能发生.

分配变量的顺序完全取决于编译器的要求,并且您不应编写依赖于任何特定顺序的代码.编译器可能会按照声明的顺序或按名称的字母顺序对局部变量进行布局,或者可能会将一些变量组合在一起,如果碰巧会导致更快的代码.

如果需要按特定顺序分配变量,则可以将它们包装在数组或结构中.

(如果您要查看生成的机器代码,您很可能会发现变量不是一个接一个地压入堆栈".相反,编译器可能会生成一条指令来调整堆栈通过一定数量的字节指针,有效地分配单个内存块来保存函数或块的所有局部变量,然后访问给定变量的代码将使用其在堆栈帧中的偏移量.)

并且由于您的函数对其局部变量不做任何事情,因此编译器可能根本不会理会为它们分配空间,特别是如果您请求使用 -O3 或类似方法进行优化的话./p>

void
f
    ()
{
    int a[1];
    int b;
    int c;
    int d[1];
}

I have found that these local variables, for this example, are not pushed on to the stack in order. b and c are pushed in the order of their declaration, but, a and d are grouped together. So the compiler is allocating arrays differently from any other built in type or object.

Is this a C/C++ requirement or gcc implementation detail?

解决方案

The C standard says nothing about the order in which local variables are allocated. It doesn't even use the word "stack". It only requires that local variables have a lifetime that begins on entry to the nearest enclosing block (basically when execution reaches the {) and ends on exit from that block (reaching the }), and that each object has a unique address. It does acknowledge that two unrelated variables might happen to be adjacent in memory (for obscure technical reasons involving pointer arithmetic), but doesn't say when this might happen.

The order in which variables are allocated is entirely up to the whim of the compiler, and you should not write code that depends on any particular ordering. A compiler might lay out local variables in the order in which they're declared, or alphabetically by name, or it might group some variables together if that happens to result in faster code.

If you need to variables to be allocated in a particular order, you can wrap them in an array or a structure.

(If you were to look at the generated machine code, you'd most likely find that the variables are not "pushed onto the stack" one by one. Instead, the compiler will probably generate a single instruction to adjust the stack pointer by a certain number of bytes, effectively allocating a single chunk of memory to hold all the local variables for the function or block. Code that accesses a given variable will then use its offset within the stack frame.)

And since your function doesn't do anything with its local variables, the compiler might just not bother allocating space for them at all, particularly if you request optimization with -O3 or something similar.

这篇关于gcc如何将局部变量压入堆栈?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆