0

I was debugging a program when I found out that if I declared two variables, foo and then bar, and if I watched the memory with a debugger, foo is stored after bar.

For instance, if I debug this program:

int main()
{
    char foo[6] = "hello";
    char bar[12] = "hello world";
    return 0;
}

GDB tells me that bar begins at 0x7fffffffe6ae and ends 13 chars later, and foo begins at 0x7fffffffe6ba and ends 6 characters later, so the address of foo is greater than the bar address.

So why foo is stored after bar in memory, even if foo is declared before bar?

GtN
  • 57
  • 4
  • The compiler can make the decision on local variable storage , the standard does not require any ordering. You might see different behaviour in other compilers – M.M Jun 15 '20 at 21:24
  • Depends on your point of view anyway. If the stack grows downwards, then `foo` was stored first. – Weather Vane Jun 15 '20 at 21:27

0 Answers0