I have been trying to get the amount of memory allocated by my C++ program. For testing purposes I created a structure:
struct player {
string name;
int id;
player(string _name, int _id) : name(_name), id(_id) {}
player(){};
void set(string _name, int _id){
name = _name;
id = _id;
}
string tostring() {
return ("{name: " + name + ", id: " + to_string(id) + "}");
}
};
And this is what I am doing in my main function:
player* players;
players = new player[4]();
players[0].set("a", 1);
players[1].set("b", 2);
players[2].set("c", 3);
players[3].set("d", 4);
for(int i = 0; i < 4; i ++) {
cout << players[i].tostring() << endl;
}
delete [] players;
So i want to print the amount of allocated memory before and after the "delete" operator. I have tried to do it in two ways, suggested by this thread. 1)
size_t getMemoryUsage() {
PROCESS_MEMORY_COUNTERS memCounter;
BOOL result = GetProcessMemoryInfo(GetCurrentProcess(), &memCounter, sizeof( memCounter ));
SIZE_T physMemUsedByMe = memCounter.WorkingSetSize;
return physMemUsedByMe;
}
Assuming this gives the memory, mapped to my process in bytes, the result I get is always something around 18.7 Mbytes. But every time I run it, I get slightly different result. Also, after I call the delete operator, I get 18.8 Mbytes. So after I free memory, the memory I use raises???
2)
void printMemoryStatus()
{
MEMORYSTATUSEX statex;
statex.dwLength = sizeof (statex);
GlobalMemoryStatusEx (&statex);
cout << (statex.ullTotalVirtual - statex.ullAvailVirtual) << endl;
}
Also assuming this result is in bytes, I get 145.273 Mbytes in the output.
The size of my structure is 28 bytes, so my program should use something at least close to 112 bytes. so neither of those two methods are what i need. How can I get the amount of memory my program uses without any external tools.
My headers are:
#include <stdlib.h>
#include <iostream>
#include <fstream>
#include <windows.h>
#include <psapi.h>
#include <tchar.h>
I am compiling with MinGW in codeblocks, with the psapi library as a linked library. My g++ version is 9.2.0 on Windows 10.