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.
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:
On my system, this results in:
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.