【问题标题】:Why the function address is different before and after I run the code?为什么我运行代码前后函数地址不一样?
【发布时间】:2021-04-29 03:32:40
【问题描述】:

源代码在这里

#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;
}

并用gcc -O0 gcd.c -o gcd -g编译

在我运行 gcd 之前,gcd() 地址是0x1169。 我运行之后,同一个函数的地址变成了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>

为什么在运行代码之前和之后会有这样的差异?

【问题讨论】:

标签: c gdb function-address


【解决方案1】:

这是由于Address Space Layout Randomization。简而言之,这意味着模块/库/可执行文件每次加载时都会位于不同的地址。

【讨论】:

  • 对不起,我不太明白,我的意思是它想做ASLR保护,但是为什么运行代码后会显示真实地址?
  • 因为您使用调试器来检查它。
  • 这里的问题不是地址空间随机化,而是位置独立的可执行文件。默认情况下,GDB 关闭地址空间随机化。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-04-17
  • 1970-01-01
  • 2019-03-12
  • 1970-01-01
相关资源
最近更新 更多