As per the standard, when the destructor of a std::unordered_map is called (for example when it leaves the scope it is created in), one expects the memory it allocates to be freed. However a simple experiment I have ran on multiple machines seems to conflict with this? Consider the following program:
#include <chrono>
#include <iostream>
#include <map>
#include <unordered_map>
#include <memory>
#include <thread>
#include <vector>
void CreateMap() {
std::unordered_map<int, int> testMap;
for (int i=0; i < 10000000; i++) {
testMap[i] = 5;
}
std::cout << "finished building map" << std::endl;
std::this_thread::sleep_for (std::chrono::seconds(15));
std::cout << "about to exit from CreateMap()" << std::endl;
}
int main()
{
CreateMap();
CreateMap();
CreateMap();
while (true) {
std::this_thread::sleep_for(std::chrono::seconds(1));
}
return 0;
}
On my machine, 10% RAM is consumed when the map is finished building but we sleep at the end in CreateMap(). However after exiting the RAM only goes down to 8% (one can play with various sizes of the map to show that the map itself is responsible for more than 2%) so one would expect that CreateMap is leaking memory? However 3 calls to CreateMap() or just one call seem to not make a difference (so the memory is recycled to the program but not the RAM?).
Could this be something strange about OS memory management that I don't understand ,i.e., it is possible for a program to free memory for its own future use (future allocations) but not to the OS (i.e., for memory allocations in other programs)?