Morgan Wilde
Morgan Wilde

Reputation: 17295

How to explain the order of memory address assignment?

I want to figure out how the memory addresses are allocated to each variable, so I have the following code:

#include <stdio.h>

int main() {

    int males;
    int females;

    printf("Address of 'int females': %p\n", (void *)&females);
    printf("Address of 'int males':   %p\n", (void *)&males);

    return 0;
}

When I compile it with cc and run the program, I get this output:

Address of 'int females': 0x7fff54f52b34
Address of 'int males':   0x7fff54f52b38

But the order in which I allocated int males and int females is different to the addresses. The output shows that int females address is a smaller number, why is that?

My intuition was to see int males have the address 0x7fff54f52b34, and then 4 bytes later, int females allocated at 0x7fff54f52b38.

Compiler

Apple LLVM version 4.2 (clang-425.0.28) (based on LLVM 3.2svn)
Target: x86_64-apple-darwin12.5.0
Thread model: posix

Upvotes: 0

Views: 531

Answers (1)

Kerrek SB
Kerrek SB

Reputation: 476960

The burden is on you: Why did you imagine that there was any kind of rule about the addresses of local variables? According to the language standard, you are not even allowed to compare two addresses for ordering.

Upvotes: 2

Related Questions