Does stack grow upward or downward?

Viewed 88616

I have this piece of code in c:

int q = 10;
int s = 5;
int a[3];

printf("Address of a: %d\n",    (int)a);
printf("Address of a[1]: %d\n", (int)&a[1]);
printf("Address of a[2]: %d\n", (int)&a[2]);
printf("Address of q: %d\n",    (int)&q);
printf("Address of s: %d\n",    (int)&s);

The output is:

Address of a: 2293584
Address of a[1]: 2293588
Address of a[2]: 2293592
Address of q: 2293612
Address of s: 2293608

So, I see that from a to a[2], memory addresses increases by 4 bytes each. But from q to s, memory addresses decrease by 4 byte.

I wonder 2 things:

  1. Does stack grow up or down? (It looks like both to me in this case)
  2. What happen between a[2] and q memory addresses? Why there are a big memory difference there? (20 bytes).

Note: This is not homework question. I am curious on how stack works. Thanks for any help.

14 Answers

It depends on the architecture. To check your own system, use this code from GeeksForGeeks:

// C program to check whether stack grows 
// downward or upward. 
#include<stdio.h> 

void fun(int *main_local_addr) 
{ 
    int fun_local; 
    if (main_local_addr < &fun_local) 
        printf("Stack grows upward\n"); 
    else
        printf("Stack grows downward\n"); 
} 

int main() 
{ 
    // fun's local variable 
    int main_local; 

    fun(&main_local); 
    return 0; 
} 
Related