I was trying to track memory occupied by my c++ project, so I found a function which could print RSS with shared memory & private memory from this post. Code is shown below
void testMemoryOccupied() {
int tSize = 0, resident = 0, share = 0;
ifstream buffer("/proc/self/statm");
buffer >> tSize >> resident >> share;
buffer.close();
long page_size_kb = sysconf(_SC_PAGE_SIZE) / 1024; // in case x86-64 is configured to use 2MB pages
double rss = resident * page_size_kb;
cout << "RSS - " << rss << " kB\n";
double shared_mem = share * page_size_kb;
cout << "Shared Memory - " << shared_mem << " kB\n";
cout << "Private Memory - " << rss - shared_mem << "kB\n";
cout << endl;
}
And I tried to test whether this would work, so I wrote:
testMemoryOccupied();
int* foo = new int[10000];
for (int i=0;i<10000;i++) {
foo[i] = i;
}
testMemoryOccupied();
int* foo1 = new int[10000];
for (int i=0;i<10000;i++) {
foo1[i] = i;
}
testMemoryOccupied();
delete[] foo;
testMemoryOccupied();
free(foo1);
testMemoryOccupied();
The result showed out that RSS only increased after those two for loops, but not decreased after delete[] or free().
RSS - 1576 kB
Shared Memory - 1356 kB
Private Memory - 220kB
RSS - 1772 kB
Shared Memory - 1516 kB
Private Memory - 256kB
RSS - 1812 kB
Shared Memory - 1516 kB
Private Memory - 296kB
RSS - 1812 kB
Shared Memory - 1516 kB
Private Memory - 296kB
RSS - 1812 kB
Shared Memory - 1516 kB
Private Memory - 296kB
I know "deleting" only marks some memory locations to be "usable" but not actually wiping them out, is that the reason why RSS remains the same here?
If that is the case, how could I track the actual memory occupied at some point during the program?