Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does variable's address change each time debugging [duplicate]

Tags:

c

debugging

gdb

I'm new to GDB and is curious about if varaible's address will change or not, during different debugging?

The code I'm using:

#include <stdio.h>
int main()
{
   char * p = malloc(10);
   printf("heap=%p stack=%p\n", p, &p);
}

Compile:gcc main.c -g

And for 3 times in my Ubuntu, the GDB console, all gives same:

gdb$ b 5
Breakpoint 1 at 0x4005fb: file main4.c, line 5.
gdb$ r
Starting program: /home/zz/work/bold/src/a.out
Breakpoint 1, main () at main4.c:5
gdb$ p &p
$1 = (char **) 0x7fffffffe060

However, running the compiled (debuggable) a.out file twice, it gives different output for &p:

heap=0x1c47010 stack=0x7ffd2df09b50
heap=0x25a5010 stack=0x7ffd757125f0

Will GDB guarantee any variable is with same address during different debugging time or not, and why?

Also, why just running instead of debugging seems using different scheme?

like image 511
ChrisZZ Avatar asked Apr 29 '20 11:04

ChrisZZ


People also ask

Which is not a way to check the value of a variable while debugging in Eclipse?

You can not check local variable unless you are in the method. As local variables have scope of the block of the method, they will be inaccessible unless method is executing and thus you are getting "variable can not be resolved" message.

Is it possible to change the value of a variable while debugging?

yes ,it is possible to change the value of a variable while debugging in a c# application .


1 Answers

Most Linux systems have address space layout randomisation enabled (ASLR). With ASLR many parts of the address space, including executable, heap and stack, are loaded at random address each time. That's what you see when you run the a.out directly.

GDB by default disables ASLR to make debugging more predictable. That is a configurable option and can be turned on or off. From the GDB manual:

set disable-randomization

set disable-randomization on

This option (enabled by default in GDB) will turn off the native randomization of the virtual address space of the started program. This option is useful for multiple debugging sessions to make the execution better reproducible and memory addresses reusable across debugging sessions.

set disable-randomization off

Leave the behavior of the started executable unchanged.

like image 146
kaylum Avatar answered Oct 16 '22 09:10

kaylum