Why printing an address changes their address?

Viewed 50

Consider this code:

    int a = 2;
    int b = 5;
    int c = 7;

When compiling it stores them in the order I assign them:

main:
        push    rbp
        mov     rbp, rsp
        mov     DWORD PTR [rbp-4], 2 ; int a = 2
        mov     DWORD PTR [rbp-8], 5 ; int b = 5
        mov     DWORD PTR [rbp-12], 7 ; int c = 7
        ...

But if I decide to print the address of b, now b switched with c their addresses:

    int a = 2;
    int b = 5;
    int c = 7;
    printf("%d\n", &b);
main:
        push    rbp
        mov     rbp, rsp
        sub     rsp, 16
        mov     DWORD PTR [rbp-4], 2 ; int a = 2
        mov     DWORD PTR [rbp-12], 5 ; int b = 5
        mov     DWORD PTR [rbp-8], 7 ; int c = 7
        ...

So why do they switch addresses? By the way, I'm using gcc 12.2.

1 Answers

The Compiler Explorer uses gcc 12.2 and does not show this behaviour.

I tried compiling this code myself and gdb shows the "correct" order.

#include "stdio.h"
int main()
{
    int a=2;
    int b=5;
    int c=7;
    printf("%d", b);
    return 0;
}

gdb output of "disassemble main":

Dump of assembler code for function main:
0x0000000000401126 <+0>:    push   rbp
0x0000000000401127 <+1>:    mov    rbp,rsp
0x000000000040112a <+4>:    sub    rsp,0x10
0x000000000040112e <+8>:    mov    DWORD PTR [rbp-0x4],0x2
0x0000000000401135 <+15>:   mov    DWORD PTR [rbp-0x8],0x5
0x000000000040113c <+22>:   mov    DWORD PTR [rbp-0xc],0x7
0x0000000000401143 <+29>:   mov    eax,DWORD PTR [rbp-0x8]
0x0000000000401146 <+32>:   mov    esi,eax
0x0000000000401148 <+34>:   mov    edi,0x402010
0x000000000040114d <+39>:   mov    eax,0x0
0x0000000000401152 <+44>:   call   0x401030 <printf@plt>
0x0000000000401157 <+49>:   mov    eax,0x0
0x000000000040115c <+54>:   leave  
0x000000000040115d <+55>:   ret    
End of assembler dump.
Related