+ 1

Why is the memory difference 4

#include <stdio.h> int main() { int x[100]; int y = 0; printf("%p, %p", &x , &y); return 0; } i have this basic code and i excpected the address diference to be 400 since 100 * sizeof(int) is 400 but unless i use the variables somwhere the memory doesen't seem to be allocated.

14th Jul 2020, 5:42 PM
Eren
Eren - avatar
5 Answers
+ 1
It says no where in the standard that variables should be allocated in the order they are defined, it's an implementation detail that can change per compiler. GCC tends to allocate them in reverse order if you have optimizations turned off, but if you enable optimizations than the thing in the paper if applied. For me, without optimizations enabled my gcc allocates them in the same order as you, Jayakrishna. With optimizations enabled it allocates it it like: z, y, v, a, x for me, again, x is last. No idea how other compilers implement it, though.
14th Jul 2020, 7:45 PM
Dennis
Dennis - avatar
+ 1
There first "y getting allocation then x. That's why... I think, We can expect - Arrays will gets allocated continues memory locations but other normal variables gets allocated depends on compiler...
14th Jul 2020, 6:26 PM
Jayakrishna šŸ‡®šŸ‡³
+ 1
Apparently allocating a big array like x last is more efficient. Might want to read this paper: https://gcc.gnu.org/pub/gcc/summit/2003/Optimal%20Stack%20Slot%20Assignment.pdf
14th Jul 2020, 6:35 PM
Dennis
Dennis - avatar
+ 1
I think what he mean is, first x sholud be allocated then y. I thought depends on compiler but no. Depends flow of execution first x then y should get memory allocation as first to be pushed to stack first gets... But here I think last getting first memory allocation, towards the first one pushed to stack.. Dennis is this the way same happens for every program? or there a sequence for it.. I added 2 more and observed it.. that fisrt v, then, y, x, z getting locations.... #include <stdio.h> int main() { int z=0, x[100], y = 0, v; float a; printf("%ld, %ld %ld %ld %ld", &z , &x, &y, &v, &a); return 0; }
14th Jul 2020, 6:52 PM
Jayakrishna šŸ‡®šŸ‡³
+ 1
Dennis thanks for the clarification... Hope it helps for the questioner also...
15th Jul 2020, 5:14 PM
Jayakrishna šŸ‡®šŸ‡³