0

I wonder how memory is allocated in c. In the example below, it looks like the compiler allocates some memory for the program and then goes backward. How and why does it work like that?

Code:

int main (void) {
    int a;
    int b;
    int c, d;

    printf("a: %p\nb: %p\nc: %p\nd: %p\n", &a, &b, &c, &d);
}

Output:

a: 0x7ffff275351c
b: 0x7ffff2753518
c: 0x7ffff2753514
d: 0x7ffff2753510
adler
  • 61
  • 8
  • `a` was pushed on the stack first, so it has the highest address. But the compiler can store these local variable wherever and however it pleases, as long as the behaviour conforms to the C Standard. – Weather Vane Apr 05 '21 at 16:05

2 Answers2

0

This depends on the architecture, but on many systems local variables are stored on the stack. For the compiler it is not strictly necessary to populate the stack top down, so this is depending on the compiler implementation. Usually the compiler saves enough space on the stack and organizes it, as it sees fit.

The compiler may not even put it in memory, but can place the values directly in registers instead, as long as the observable behavior stays the same.

Devolus
  • 21,661
  • 13
  • 66
  • 113
0

This strongly depends on the specific implementation. The language itself only specifies minimal rules for where and how memory is allocated for different objects (see the C 2011 Online Draft, section 6.2.4., for the complete set of rules).

In most implementations, auto variables (i.e., "local" variables) are created on the stack. While implementations are not required to create variables in the same order in which they are declared, it's not uncommon for them to do so.

On x86/x86-64, the stack grows "downwards" towards decreasing addresses, so each item pushed onto the stack will have a lower address than the previous item.

John Bode
  • 119,563
  • 19
  • 122
  • 198