Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does my stack grow upward instead of downward? [duplicate]

Tags:

c

gcc

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?

like image 295
so.very.tired Avatar asked Sep 30 '22 03:09

so.very.tired


1 Answers

tl;dr Using the code in your question, we can't tell.

The order in which local variables appear on the stack is up to the compiler. It might reorder things, or it might even not allocate stack space for certain variables (because they got optimised away, or got allocated to registers).

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

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

In order to compile the code that takes the addresses of a1, a2 and a3, the compiler has to go out of its way to store the values of the three registers in what are effectively three unnamed local variables:

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

In summary, the code in your question is insufficient to conclude which way the stack grows.

Luckily, we know this sort of thing a priori or can figure it out using different code: What is the direction of stack growth in most modern systems?

like image 100
NPE Avatar answered Oct 13 '22 00:10

NPE