Order of variables in the stack (GCC) [duplicate]

◇◆丶佛笑我妖孽 提交于 2019-12-11 08:47:23

问题


When compiling C code in GCC, is there any way to guarantee that the stack variables will appear in the stack in the order i declare them (or in reversed order, doesn't matter to me)? I know this is possible via structs but I would rather not use them.


回答1:


The only way would be a struct which includes all variables in the order you like.

For local variables the compiler is free to reorder/reuse variables at any order it suits her. Some variables may not have a memory location at all, they live only in registers, others will be optimized away completely.




回答2:


If you are adamant that you do not want to use a struct then you will have to allocate the stack memory yourself with alloca(). But then you will need to manage your local variables manually within that block of stack memory.

I would not recommend that you do this. Use a struct.




回答3:


The most reliable approach is to direct gcc to produce assembly language output using gcc -S, and examine the assembly language output to find out which variables have been put where. If you compile without optimisations, the variables probably won't get removed or rearranged, and if you assign different values to each local variable it should be easy to spot each one.

I admit that this is not very high-tech. But if you want to be sure that gcc is generating code that works in a particular way, you will have to look at the code it generates...



来源:https://stackoverflow.com/questions/9535342/order-of-variables-in-the-stack-gcc

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!