2

the source code is here

#include <stdio.h>

int gcd(a, b) {
  if (b == 0) return a;
  return gcd(b, a % b);
}

int main(int argc, char **argv) {
  int a = atoi(argv[1]);
  int b = atoi(argv[2]);
  int res = gcd(a, b);
  printf("%d\n", res);
  return 0;
}

and compiled with gcc -O0 gcd.c -o gcd -g

Before I run gcd, the gcd() address is 0x1169. After I run it, the address of the same function becomes to 0x555555555169.

$ gdb -q gcd
Reading symbols from gcd...

(gdb) p gcd
$1 = {int (int, int)} 0x1169 <gcd>

(gdb) run 42 24
Starting program: ~/Workstation/gcd 42 24
6
[Inferior 1 (process 104126) exited normally]

(gdb) p gcd
$2 = {int (int, int)} 0x555555555169 <gcd>

Why there're such a difference between before and after running the code?

Ca Chen
  • 63
  • 8
  • 1
    Does this answer your question? [Movement of \`main\` function after running in gdb?](https://stackoverflow.com/questions/57873573/movement-of-main-function-after-running-in-gdb) – Mark Plotnick Apr 29 '21 at 06:28
  • @MarkPlotnick I think it not really answer the question, why the address relocated after execution? – Ca Chen Apr 29 '21 at 06:51
  • 1
    Here’s another answer that goes into more detail. [Why do the addresses in my assembler dump differ from the addresses of registers?](https://stackoverflow.com/a/53311089/2554472) – Mark Plotnick Apr 29 '21 at 07:16
  • @MarkPlotnick Thank you so much, this is exactly what I want to know! :) – Ca Chen Apr 29 '21 at 09:29

1 Answers1

0

This is due to Address Space Layout Randomization. In short, it means that modules/libs/executables will be at a different address each time being loaded.

Thien
  • 64
  • 3
  • sorry, I don't really understand it, I mean as it want to do ASLR for protection, but why it reveals the real address after running the code? – Ca Chen Apr 29 '21 at 06:45
  • because your were using a debugger to inspect it. – Thien Apr 29 '21 at 07:38
  • 1
    It's not address space randomization, rather position independent executables, that are the problem here. By default GDB turns off address space randomization. – Andrew Apr 29 '21 at 09:51