Is it possible to get the remaining available memory on the system (x86, x64, PowerPC / Windows, Linux or MacOS) in standard C ++ 11 without failures?
The naive way is to try to allocate very large arrays, starting from too large, catch exceptions every time it fails, and reduce the size until an exception is thrown. But maybe there is a more efficient / smart method ...
EDIT 1: Actually, I don't need the exact amount of memory. I would like to know approximately (error line 100 MB) how much my code could use when I start it.
EDIT 2: What do you think of this code? Is it safe to run it at the beginning of my program or can it spoil the memory?
#include <iostream> #include <array> #include <list> #include <initializer_list> #include <stdexcept> int main(int argc, char* argv[]) { static const long long int megabyte = 1024*1024; std::array<char, megabyte> content({{'a'}}); std::list<decltype(content)> list1; std::list<decltype(content)> list2; const long long int n1 = list1.max_size(); const long long int n2 = list2.max_size(); long long int i1 = 0; long long int i2 = 0; long long int result = 0; for (i1 = 0; i1 < n1; ++i1) { try { list1.push_back(content); } catch (const std::exception&) { break; } } for (i2 = 0; i2 < n2; ++i2) { try { list2.push_back(content); } catch (const std::exception&) { break; } } list1.clear(); list2.clear(); result = (i1+i2)*sizeof(content); std::cout<<"Memory available for program execution = "<<result/megabyte<<" MB"<<std::endl; return 0; }
source share