局部变量分配的堆栈顺序 [英] Order of local variable allocation on the stack

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

问题描述

在这两个函数看看:

void function1() {
    int x;
    int y;
    int z;
    int *ret;
}

void function2() {
    char buffer1[4];
    char buffer2[4];
    char buffer3[4];
    int *ret;
}

如果我在突破功能1() GDB ,并打印变量的地址,我得到这个

If I break at function1() in gdb, and print the addresses of the variables, I get this:

(gdb) p &x  
$1 = (int *) 0xbffff380
(gdb) p &y
$2 = (int *) 0xbffff384
(gdb) p &z
$3 = (int *) 0xbffff388
(gdb) p &ret
$4 = (int **) 0xbffff38c

如果我做同样的事情在函数2(),我得到这样的:

If I do the same thing at function2(), I get this:

(gdb) p &buffer1
$1 = (char (*)[4]) 0xbffff388
(gdb) p &buffer2
$2 = (char (*)[4]) 0xbffff384
(gdb) p &buffer3
$3 = (char (*)[4]) 0xbffff380
(gdb) p &ret
$4 = (int **) 0xbffff38c

您会注意到,在这两种功能, RET 存储最接近堆栈的顶部。在功能1(),它后面是以Z ,终于 X 。在函数2() RET 后跟缓冲器1 ,那么缓冲器2 buffer3 。为什么存储顺序变了?我们使用这两种情况下相同的内存量(4字节 INT s和4个字节字符阵列)因此它不能被填充的问题。莫不是什么原因造成的重新排序,此外,是否可以通过看C code到确定的时间提前局部变量将如何订购?

You'll notice that in both functions, ret is stored closest to the top of the stack. In function1(), it is followed by z, y, and finally x. In function2(), ret is followed by buffer1, then buffer2 and buffer3. Why is the storage order changed? We're using the same amount of memory in both cases (4 byte ints vs 4 byte char arrays), so it can't be an issue of padding. What reasons could there be for this reordering, and furthermore, is it possible by looking at the C code to determine ahead of time how the local variables will be ordered?

现在我知道了ANSI规范对C只字未提局部变量保存在与编译器被允许选择自己的订单的订单,但我想,编译器有规则,但它如何负责这一点,并解释,为什么这些规则被做是因为它们。

Now I'm aware that the ANSI spec for C says nothing about the order that local variables are stored in and that the compiler is allowed to chose its own order, but I would imagine that the compiler has rules as to how it takes care of this, and explanations as to why those rules were made to be as they are.

有关在Mac OS 10.5.7参考我使用GCC 4.0.1

For reference I'm using GCC 4.0.1 on Mac OS 10.5.7

推荐答案

我不知道的为什么海合会组织及其栈它(的方式虽然我想你可以破解打开其来源或的this纸并查找出来),但我可以告诉你如何保证特定的堆栈变量的顺序如果由于某种原因,你需要。简单地把它们放在一个结构:

I've no idea why GCC organizes its stack the way it does (though I guess you could crack open its source or this paper and find out), but I can tell you how to guarantee the order of specific stack variables if for some reason you need to. Simply put them in a struct:

void function1() {
    struct {
        int x;
        int y;
        int z;
        int *ret;
    } locals;
}

如果我没记错的正确,规范保证&放大器; RET> &安培; Z> &安培; Y> &安培; X 。我离开了我的K&安培; R在工作,所以我无法引用虽然诗句

If my memory serves me correctly, spec guarantees that &ret > &z > &y > &x. I left my K&R at work so I can't quote chapter and verse though.

这篇关于局部变量分配的堆栈顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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