Address randomization: print address of static var in c

I am reading an OS tutorial, there is an example of checking if the system supports virtual addresses and says that the next program should print the same result every time. I see some differences in my macbook pro.

#include <stdio.h> int var = 0; int main(void) { var += 1; printf("Address: %x, value: %d\n", &var, var); return 0; } 

at startup, I see the address change in some bytes (not all of them):

 ./main Address: e8c6018, value: 1 ./main Address: 9032018, value: 1 ./main Address: 1bc7018, value: 1 

When I run in GDB, I always see 1018:

 (gdb) r Starting program: /Users/xilan/temp/main Address: 1018, value: 1 [Inferior 1 (process 19631) exited normally] (gdb) r Starting program: /Users/xilan/temp/main Address: 1018, value: 1 [Inferior 1 (process 19636) exited normally] (gdb) r Starting program: /Users/xilan/temp/main Address: 1018, value: 1 [Inferior 1 (process 19654) exited normally] 

So, what makes it different in direct and in GDB? Why do I see that the address changes at startup directly?

+5
source share
2 answers

Your book is old. Many operating systems today randomize when programs and libraries load to make things a little safer for certain attacks.

MacOS randomizes where programs are loaded into memory. However, it disables this randomization for gdb, so the address always looks the same in gdb.

+2
source

In GDB, we always get the same address , we even work with different processes, but the normal behavior should be as shown below, if it runs directly on Linux

 ./main Address: e8c6018, value: 1 ./main Address: 9032018, value: 1 ./main Address: 1bc7018, value: 1 

Because this is due to the fact that GDB is disabled, randomization is indicated by default >. It should be turned off , if we expect regular output:

 set disable-randomization off 

Link Link: http://visualgdb.com/gdbreference/commands/set_disable-randomization

+2
source

Source: https://habr.com/ru/post/1260986/


All Articles