开发者

Why does the address of a local variable vary when executing multiple times, but not when debugging it with GDB?

开发者 https://www.devze.com 2023-04-11 21:47 出处:网络
Why is it that when running code from gdb, I get the same addresses for the variables declared, but while just executing the binary I don\'t get the same addresses.

Why is it that when running code from gdb, I get the same addresses for the variables declared, but while just executing the binary 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 dur开发者_JAVA技巧ing 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 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 execution of the program always produces a SEGFAULT.

$ ./a.out   
Segmentation fault

I don't know if this question is a duplicate of Is this always the address for GDB debug program?

NOTE: I have not switched off ASLR


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

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

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


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

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号