1

After looking at the following code, is my assumption correct that C at first tries to assign a certain address to a variable? And when there are more variables needed 4 bytes are subtracted from some address.

In this example it would be 0x7fff15745074.

#include <stdio.h>

void f1(){
        int one = 1;
        printf("\t\t\t\t\t\t&one:\t%p\n", &one);
}

void f2(){
        int two = 2;
        printf("\t\t\t\t\t\t&two:\t%p\n", &two);
}

void f34(){
        int three = 3; int four = 4;
        printf("\t\t\t&three:\t%p\t&four:\t%p\n", &three, &four);
}

void f56(){
        int five = 5; int six = 6;
        printf("\t\t\t&five:\t%p\t&six:\t%p\n", &five, &six);
}

void f789(){
        int seven = 7; int eight = 8; int nine = 9;
        printf("&seven:\t%p\t&eight:\t%p\t&nine:\t%p\n", &seven, &eight, &nine);
}

int main() {
        f1(); f2(); f34(); f56(); f789();
}

output:

                                                &one:   0x7fff15745074
                                                &two:   0x7fff15745074
                        &three: 0x7fff15745070  &four:  0x7fff15745074
                        &five:  0x7fff15745070  &six:   0x7fff15745074
&seven: 0x7fff1574506c  &eight: 0x7fff15745070  &nine:  0x7fff15745074
tonik
  • 465
  • 1
  • 4
  • 15
  • 4
    Well, you've just discovered that your compiler uses top-down [stack allocation](https://en.wikipedia.org/wiki/Stack-based_memory_allocation). – tadman Jun 11 '20 at 20:02
  • The question is a bit unclear, but automatic variables in C are usually implemented using a stack (a last in, first out structure). – vgru Jun 11 '20 at 20:02
  • What is your question? – Tony Tannous Jun 11 '20 at 20:02
  • 1
    and the 4 that you are seeing is `sizeof(int)` – alani Jun 11 '20 at 20:03
  • 1
    Keep in mind that the "stack" should not be treated as a given, the compiler is not required to use one at all. Optimizing compilers will often skip the stack for performance reasons, passing things in via registers or by pre-computing results. As a mental model the stack works, but in practice the emitted machine code is often very different. – tadman Jun 11 '20 at 20:04
  • You could try calling `f2()` from within `f1()` and make sense of it... There is no *requirement* in C for a stack, but that is a typical mechanism used. – Weather Vane Jun 11 '20 at 20:05
  • 1
    Thank you guys, just wanted to be sure and btw @tadman I like the first part of your quote in ur bio ;) – tonik Jun 11 '20 at 20:19

0 Answers0