Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linux getrusage() maxrss maximum resident set size not increasing with allocation (C++)

I am trying to use getrusage(.) and maximum resident set size (maxrss) to check for memory leaks. However, when i purposely try to create a leak, maxrss does not change. Maybe i am not understanding maxrss deeply enough. Here is the code:

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

I get the exact same value after allocatoin (~15000kb). On Ubuntu x86.

like image 955
John.smith16 Avatar asked Oct 16 '25 09:10

John.smith16


1 Answers

Allocated memory isn't actually mapped until you access it. If you initialize the array with values, Linux is forced to actually allocate and map new pages:

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

On my system, this results in:

4900kb
Allocating...
after allocation 6844kb

Note that compiler optimizations may decide that the array is unused or should be allocated up front, so prefer compiling without them or rewriting the test case in such a way that it can't be optimized.

like image 82
that other guy Avatar answered Oct 17 '25 22:10

that other guy