为什么同一个进程 运行 两次使用的内存量并不完全相同?

Why does the same process ran twice does not use exactly the same quantity of memory?

考虑 MyProcess,一个纯粹的确定性过程。如果我 运行 这个过程多次测量 max memory 使用 usz time 我得到

time ./MyProcess
max memory:                86624 KB

time ./MyProcess
max memory:                85740 KB

time ./MyProcess
max memory:                86156 KB

RAM 使用量的测量当然非常相似,但略有不同。是什么造成了这些差异?


仅供参考,我使用 MACOSX 10.11.3

这很可能是由于地址 Space 布局随机化,又名 ASLR。

现代 OS 在每次新执行时移动和打乱进程的内存布局,这样攻击者就不知道感兴趣的地址在哪里。

通常程序员不会注意到,除非通过使用内存的微小变化或所有指针具有不同的值(例如通过以指针为键的哈希表导致不同的迭代顺序)。

这是 Linux 的示例程序,它也执行 ASLR:

#include <stdio.h>

int main() {
  char c;
  printf("Address: %lx\n", &c);
  return 0;
}

如果我们 运行 多次,我们会看到不同的地址和内存使用情况:

$ gcc foo.c -o foo

$ command time -f 'Memory: %M' ./foo
Address: 7ffc1995f2df
Memory: 1288

$ command time -f 'Memory: %M' ./foo
Address: 7ffcdfd2427f
Memory: 1324

$ command time -f 'Memory: %M' ./foo
Address: 7ffe3022a23f
Memory: 1368

如果我们禁用 ASLR(这是 Linux 特定的并且不适用于 OSX):

sudo tee /proc/sys/kernel/randomize_va_space <<< 0

地址和使用的内存始终相同:

$ command time -f 'Memory: %M' ./foo
Address: 7fffffffe4bf
Memory: 1272

$ command time -f 'Memory: %M' ./foo
Address: 7fffffffe4bf
Memory: 1272

$ command time -f 'Memory: %M' ./foo
Address: 7fffffffe4bf
Memory: 1272