Allocation order on the stack
I'm running this C code
#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);
And i get as output Allocated from -4262832 to -4197296 so for 65536 bytes Now the stack pointer is on -4262836
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 ();
开发者_JS百科 }
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);
This is the output
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).
Thank you!
You can't. And you should not care where the variables are, the compiler could optimize them entierly away anyhow.
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.
精彩评论