I'm disassembling an executable:
(gdb) disas main
Dump of assembler code for function main:
0x004012d0 <main+0>: push %ebp
0x004012d1 <main+1>: mov %esp,%ebp
...
Each time the memory address is the same:0x004012d0
.
Isn't the memory address to be dynamically assigned by the OS?
UPDATE
Now I see it's virtual space,and it can be randomized on some platforms.
Can someone post a gdb dump that changes ?
The memory addresses do get reused - depending on the operating system. Otherwise, if a program does lots of allocations and deallocations, more than there's RAM in the machine, it would not be able to continue. In the end the answer is more about the operating system and it's memory management scheme than C++ itself.
Yes, they change. The OS loads the process into different offsets each time it launches, and anything allocated with new or malloc is very likely to get different addresses each time the code is run.
The range of virtual addresses that the operating system assigns to a user or separately running program is called an address space. This is the area of contiguous virtual addresses available for executing instructions and storing data.
It depends on the OS. Most of the time the address of the binary stays the same. This is important for exploiting memory manipulation bugs, such as buffer overflows. The address of linked libraries under Linux will always be different due to ASLR. Under Windows Vista and Windows 7 the binary's virtual memory space is also randomized each time it is executed, so the function address will be different for each run.
I think the problem here (at least on Linux) might be gdb trying to help out, from the docs:
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.
This feature is implemented only on gnu/Linux. You can get the same behavior using
(gdb) set exec-wrapper setarch `uname -m` -R
http://sourceware.org/gdb/current/onlinedocs/gdb/Starting.html
UPDATE: I've now checked this and it does seem to be the case for me (running Linux 2.6.28). Compile a simple Hello World program and start gdb with no command-line args (we don't want to load the program before overriding the disable-randomization setting) and then enter:
(gdb) set disable-randomization off
(gdb) file ./a.out
(gdb) break main
(gdb) run
(gdb) disas printf
The address of printf is different each time the program is run.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With