9

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?

ChrisZZ
  • 1,521
  • 2
  • 17
  • 24

1 Answers1

10

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.

kaylum
  • 13,833
  • 2
  • 22
  • 31
  • As a note: GDB only does this for program started within GDB itself, it cannot disable randomization of an already running process when attaching to it. – Marco Bonelli Apr 29 '20 at 13:10