Why does the local variable address change when executed several times, but not when debugging using GDB?

Why, when I run the code from gdb, I get the same addresses for the declared variables, but when I simply execute the binary code, I donโ€™t get the same addresses.

#include<stdio.h> void main() { int *x,q; //I saw the address of the variable q in this program through gdb during the __1st__ execution. //I re-compiled the program to make x to point to this address. x=0x7fffffffe2bc; *x=3; printf("%d",(*x)); } 

I ran the program through gdb and it was never Segfaulted.

 $ gdb -q ./a.out Reading symbols from /home/eknath/needed2/a.out...done. (gdb) r Starting program: /home/eknath/needed2/a.out 3 Program exited normally. (gdb) q $ 

But normal program execution always causes SEGFAULT.

 $ ./a.out Segmentation fault 

I do not know if this question is a duplicate. Is it always the address for the GDB debugging program?

NOTE. I did not disable ASLR

+6
source share
2 answers

The reason you always get the same address for local variables while working in GDB is because GDB (to simplify most debugging scenarios) disables address space randomization.

You can ask GDB not to do this with set disable-address-randomization off .

For curiosity, disabling address randomization for the current process does not require any privileges and is done by calling personality(2) . Here is the patch that added this feature.

+2
source

EDIT: Let me clarify my point, as it may be unclear. GDB disables ASLR by default, so your variables will always have the same address (unless the code changes, adding variables or code before or even after, in some cases, can cause shifts in the assigned addresses and cause a crash) . This way your code succeeds because hardcoded addresses will be in the same place while working in GDB. This helps in debugging, as addresses will not change from debugging a session to debugging a session.

0
source

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


All Articles