堆栈上的分配顺序 [英] Allocation order on the stack

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

问题描述

我正在运行此C代码

#define STACKSIZE       65536    

            char d[STACKSIZE];
            if (((int) &d[STACKSIZE-1]) - ((int) &d[0]) + 1 != STACKSIZE) {
                 Printf ("Stack space reservation failed\n");
                 Exit ();
            } 

            printf("Allocated from %d to %d so for %d bytes\n", &d, d+sizeof(d), sizeof(d));

            auto int a = 3;
            printf("Now the stack pointer is on %d\n",&a);

我得到了输出从-4262832到-4197296分配为65536字节现在堆栈指针位于-4262836

And i get as output Allocated from -4262832 to -4197296 so for 65536 bytes Now the stack pointer is on -4262836

这意味着将变量"a"放在数组之后的堆栈中.但是,如果我使用可变长度数组(长度在运行时中设置的数组),则会得到相反的行为:将a放在数组之前的堆栈中.

This means that the variable "a" is put on the stack AFTER the array. But if I use a variable length array (an array whose length is setted in run time) I get the opposite behaviour: a is put on the the stack BEFORE the array.

这是代码(相同,但是在运行时设置了数组的大小)

This is the code (it is the same but the size of the array is setted in runtime)

 #define STACKSIZE       65536    

            int i = 1;
            char d[i*STACKSIZE];
            if (((int) &d[STACKSIZE-1]) - ((int) &d[0]) + 1 != STACKSIZE) {
                 Printf ("Stack space reservation failed\n");
                 Exit ();
            } 

            printf("Allocated from %d to %d so for %d bytes\n", &d, d+sizeof(d), sizeof(d));

            auto int a = 3;
            printf("Now the stack pointer is on %d\n",&a);

这是输出

从-4262856分配到-4197320,因此为65536字节现在,堆栈指针位于-4197312

Allocated from -4262856 to -4197320 so for 65536 bytes Now the stack pointer is on -4197312

那么,什么问题呢?我该如何解决(使用可变长度数组并将变量放在堆栈之后).

So, what is the problem? How can I solve it (using variable length array and putting variables on the stack after it).

谢谢!

推荐答案

您不能.而且您不必担心变量在哪里,编译器可以通过任何方式对它们进行全面优化.

You can't. And you should not care where the variables are, the compiler could optimize them entierly away anyhow.

尽管它高度依赖于系统,但是编译器通常只会在其他所有内容之后分配可变大小的数组,因为那样的话,增加堆栈的数量就可以使该数组成为Ruum.如果编译器将变量放在该区域之后,则必须通过动态大小数组的大小间接访问它们.

Although it's highly system dependent, compilers will typically just allocate variable sized arrays after everything else, since then it's just a matter of growing the stack to make ruum for the arrays. If the compiler put variables after that area it'd have to access them indirectly via the sizes of the dynamic sized arrays.

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

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