0

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
Morgan Wilde
  • 16,795
  • 10
  • 53
  • 99

1 Answers1

2

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.

Kerrek SB
  • 464,522
  • 92
  • 875
  • 1,084
  • I don't want to compare them in a program, I just want to get down to the reasoning of how would they be put in memory. But it's difficult to do that now, since there are two conflicting answers... – Morgan Wilde Nov 17 '13 at 12:53
  • 1
    But you *are* asking about a comparative property, and I'm telling you that this property you're after doesn't exist. It's like asking why Unicorns are green. Compilers can lay out local variables any way they like, and it's perfectly common for compilers to perform rather nontrivial reorderings. You should check your compiler's codegen and optimization code to understand what design decisions the authors of the compiler made. – Kerrek SB Nov 17 '13 at 13:39
  • I definitely got what I wanted out of this, so thanks a second time, I really appreciate your time. – Morgan Wilde Nov 17 '13 at 13:44