To my best understanding, the stack suppose to grow downward.
I tried to run this code:
#include<stdio.h>
void func(char* a1, int a2, int a3) {
char b1[10];
int b2;
int b3;
printf("a3 address is: %p\n", &a3);
printf("a2 address is: %p\n", &a2);
printf("a1 address is: %p\n", &a1);
printf("-----------------------\n");
printf("b1 address is: %p\n", &b1);
printf("b2 address is: %p\n", &b2);
printf("b3 address is: %p\n", &b3);
}
int main() {
func("string",2,3);
return 0;
}
And the result was not as I expected:
a3 address is: 0x7fff68473190
a2 address is: 0x7fff68473194
a1 address is: 0x7fff68473198
-----------------------
b1 address is: 0x7fff684731b0
b2 address is: 0x7fff684731a8
b3 address is: 0x7fff684731ac
I don't expect b1
,b2
,b3
to be ordered in the same way I declared them. I understand that the compiler might change that order to enable optimizations and alignment, but why is it seems like the stack grows towards high addresses instead of lower addresses?