Reputation: 17268
In C++ how would I check how much available RAM i have?
I am on windows, but be interested for Unix answers as well as windows.
Upvotes: 4
Views: 11324
Reputation: 14467
Windows: GlobalMemoryStatusEx. MSDN page has a detailed C sample code.
Linux: check the "/proc/meminfo" file (discussion)
OSX: see this SO thread Determine physical mem size programmatically on OSX
The question is not clear, however. There is physical memory, there is virtual memory, there is an OS ability to swap some unused pages to disk/other storage.
If you need to write some kind of a system monitor, then my answer would do.
If you need to be sure that none of your malloc()/new[] calls fail, then just catch appropriate exceptions or handle NULL results. The other option is to build your own allocator which gets a large memory block at the beginning and allocates smaller blocks there.
EDIT: answer to comment
The calls to WinAPI's MapViewOfFile and CreateFileMapping provide error codes to exclude fatal situations. Since files are mapped to the virtual address space shared with your process' data, you may check if there are sufficient number of pages available. I.e., if you're on a 32-bit system, you won't be able to map the whole 8Gb file to the memory at once (but you can map its smaller parts), but on a 64-bit system the mapping possibilities are sufficient for any current needs.
Upvotes: 7