Search code examples
cgdb

Why do I get the wrong address for a variable in gdb when using p &var?


I have a simple c program:


int x = 0;

void main() {
        int y = 1;
        printf("x: %d\n", x);
        printf("y: %d\n", y);
        printf("&x: %p\n", (void*) &x);
        printf("&y: %p\n", (void*) &y);
}

which I have compiled with gcc -g simple.c

Now I run ./simple and get:

&x: 0x557123835014
&y: 0x7ffcad2a35f4

But when I try to retrieve the address with gdb, I get a different result. My steps:

gdb ./simple

(gdb) b main

(gdb) run

(gdb) step
(gdb) step

(gdb) p &x
$4 = (int *) 0x555555558014 <x>
(gdb) p&y
$5 = (int *) 0x7fffffffde14

The values seem to be not very far away from each other, but why don't I get the same result? Let me know if you need additional information and thank you in advance for your help


Solution

  • Some operating systems randomizes addresses as a security measure. On Linux, for instance, that features is called Address Space Layout Randomization (ASLR) and enabled by default.

    By default GDB will disable address space randomization, so the addresses you see when running under GDB should be consistent. Use show disable-randomization to see if randomization has been disabled or not.

    You can always use set disable-randomization off to turn off the disabling, which will then leave randomization on (if the OS has it on by default), but that's very rarely helpful when debugging.