Does my stack go up, not down?

To my best understanding, the stack is expected to grow down.

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 what 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 do not expect b1 , b2 , b3 be ordered in the same way as I announced them. I understand that the compiler can change this order to enable optimization and alignment, but why does it seem that the stack is growing toward higher addresses and not lower ones?

+5
source share
1 answer

tl; dr Using the code in your question, we cannot say.

The order in which local variables appear on the stack depends on the compiler. It can change the order of things or even not allocate stack space for certain variables (since they have been optimized or allocated to registers).

Valid function arguments are pushed onto the stack - if at all! - dictated by your ABI platform. In my case (x86-64), three arguments are passed to the registers ( %edi , %esi and %edx ):

 main: ... movl $3, %edx movl $2, %esi movl $.LC7, %edi call func 

In order to compile code that accepts addresses a1 , a2 and a3 , the compiler must reject its path in order to store the values โ€‹โ€‹of the three registers in what effectively represents three unnamed local variables:

 func: ... movq %rdi, -56(%rbp) movl %esi, -60(%rbp) movl %edx, -64(%rbp) 

So the code in your question is not enough to conclude to what extent the stack grows.

Fortunately, we know such a thing a priori, or we can understand it using another code: What is the direction of stack growth in most modern systems? p>

+4
source

Source: https://habr.com/ru/post/1209773/


All Articles