I made two C programs which were exact copy of each other.
Compiled them on Linux using GCC compiler and obtained two separate executables.
Then I examined the assembly code of both using objdump
and found the instructions to be identical. Even the addresses of corresponding instructions in two files were the same.
The program was to print the address of a variable in it.
The programs when run produce different address and moreover the same program produces a different address when run each time.
Why address of code lines is same in the two programs but the address of variable changes even for the same program each time it is run?
I suspect that address printed on screen may be a virtual address, but if it's virtual why it can't be same each time? Is the address shown in Assembly code obtained by objdump
is also virtual?
It's due to address space layout randomization.
To quote Wikipedia:
Address space layout randomization (ASLR) is a computer security method which involves randomly arranging the positions of key data areas, usually including the base of the executable and position of libraries, heap, and stack, in a process's address space.
Benefits
Address space randomization hinders some types of security attacks by making it more difficult for an attacker to predict target addresses. For example, attackers trying to execute return-to-libc attacks must locate the code to be executed, while other attackers trying to execute shellcode injected on the stack have to find the stack first. In both cases, the related memory addresses are obscured from the attackers. These values have to be guessed, and a mistaken guess is not usually recoverable due to the application crashing.
For example, when I repeatedly run the same executable produced from the following C code on my Ubuntu 10.10 box:
#include <stdio.h>
int g = 0;
int main() {
int x = 0;
printf("%p %p\n", &x, &g);
}
The address of the local variable (x
) keeps changing, but the address of the global variable (g
) stays the same.
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