Linux getrusage() maxrss 最大驻留集大小不随分配增加(C++)

Joh*_*h16 3 c++ linux memory getrusage

我正在尝试使用getrusage(.)和最大驻留集大小 (maxrss) 来检查内存泄漏。但是,当我故意尝试造成泄漏时,maxrss 不会改变。也许我对 maxrss 的理解不够深入。这是代码:

#include <iostream>
#include <sys/time.h>
#include <sys/resource.h>
using namespace std;
int main() {
  struct rusage r_usage;
  getrusage(RUSAGE_SELF, &r_usage);
  cout << r_usage.ru_maxrss << "kb\n";
  cout << "Allocating...\n";
  int a = 100000; // have tried range of numbers
  int* memleaktest = new int[a]; // class member
  if(!memleaktest)
    cout << "Allocation failed";
  getrusage(RUSAGE_SELF, &r_usage);
  cout << "after allocation " << r_usage.ru_maxrss << "kb\n";
  return 0;
}
Run Code Online (Sandbox Code Playgroud)

allocatoin (~15000kb) 后我得到完全相同的值。在 Ubuntu x86 上。

tha*_*guy 5

分配的内存在您访问它之前实际上不会被映射。如果使用值初始化数组,Linux 将被迫实际分配和映射新页面:

#include <iostream>
#include <sys/time.h>
#include <sys/resource.h>
using namespace std;
int main() {
  struct rusage r_usage;
  getrusage(RUSAGE_SELF, &r_usage);
  cout << r_usage.ru_maxrss << "kb\n";
  cout << "Allocating...\n";
  int a = 1000000;                 // Sufficiently large
  int* memleaktest = new int[a](); // Initialized to zero
  if(!memleaktest)
    cout << "Allocation failed";
  getrusage(RUSAGE_SELF, &r_usage);
  cout << "after allocation " << r_usage.ru_maxrss << "kb\n";
  return 0;
}
Run Code Online (Sandbox Code Playgroud)

在我的系统上,这会导致:

4900kb
Allocating...
after allocation 6844kb
Run Code Online (Sandbox Code Playgroud)

请注意,编译器优化可能会决定数组未使用或应预先分配,因此更喜欢在没有它们的情况下进行编译或以无法优化的方式重写测试用例。