0

Possible Duplicate:
Order of local variable allocation on the stack

(C program on x86_64 Linux) I am trying to understand the way variables are assigned to stack memory. As I understand it, variables in a stack frame move toward lower memory addresses. The program below shows this.

int main() {
    int i = 6;
    char buffer[8];

    return 0;
}

Program was compiled as: gcc -g prog.c

Debugging shows:

(gdb) x/x &i
0x7fffffffe04c: 0x00000006
(gdb) x/x buffer
0x7fffffffe040: (random data)

The character array has a lower memory address than the integer i variable. My question is how come when the order of declarations are reversed as seen below, the integer variable i is still at a memory address greater than the character array?

int main() {
  char buffer[8];
  int i = 6;

  return 0;
}

(gdb) x/x &i
0x7fffffffe04c: 0x00000006
(gdb) x/x buffer
0x7fffffffe040: (random data)

This issue does not seem to occur for the ordering of say strictly single integer variables. If the order of integer declarations were switched, the earliest declared would have a higher memory address in the stack frame. The concern here is why this occurs for the character array. I have read this answer here in another post but I am wondering if anyone has a definitive explanation on this one.

Community
  • 1
  • 1
Johnathan1
  • 2,241
  • 5
  • 23
  • 24
  • I'm sorry but I really don't see why this question is any different than the one you linked to. The answers there are pretty good. – Emil Vikström Dec 02 '12 at 07:19
  • @Emil yes, they are 'pretty' good. However, it seems the answers in that post are more of hypotheses as opposed to answers backed by facts or referenced information. I really would like to know if anyone has something more concrete. – Johnathan1 Dec 02 '12 at 07:34
  • 3
    There isn't anything concrete. A compiler can allocate any address it sees fit to any variable, in any order. It can even use the same address for different variables that are not used at the same time. Or put the value in a register, and not allocate an address at all. – Bo Persson Dec 02 '12 at 07:38
  • 1
    Johnathan1, then put a bounty on the original question rather than creating a duplicate. I have updated the dead link in the top answer on that post, so there is even a reference. – Emil Vikström Dec 02 '12 at 07:51

0 Answers0