我在两台不同的Linux电脑上(一台是华为笔记本,8GB内存,运行Arch系统,另一台是iMac 2017,32GB内存,运行Ubuntu系统)编译和运行了下面这个C语言文件。
#include <stdio.h>
#include <sys/resource.h>
long get_mem_usage()
{
struct rusage myusage;
getrusage(RUSAGE_SELF, &myusage);
return myusage.ru_maxrss;
}
int main()
{
printf("usage: %ld\n", get_mem_usage());
return 0;
}
编译器为: gcc (Ubuntu 9.2.1-9ubuntu2) 9.2.1
gcc (Arch Linux 9.3.0-1) 9.3.0
在Ubuntu上,我一直得到:
usage: 2432
usage: 2432
usage: 2432
在 Arch 上,输出结果不一致且更加庞大:
usage: 100584
usage: 100964
usage: 100524
我对为什么这两台计算机/发行版之间的这些值有如此大的差异感到相当困惑。这种内存分配模式的原因是什么?是编译器分配了这些内存资源吗?还是内核决定了内存分配?