Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get available memory C++/g++?

I want to allocate my buffers according to memory available. Such that, when I do processing and memory usage goes up, but still remains in available memory limits. Is there a way to get available memory (I don't know will virtual or physical memory status will make any difference ?). Method has to be platform Independent as its going to be used on Windows, OS X, Linux and AIX. (And if possible then I would also like to allocate some of available memory for my application, someone it doesn't change during the execution).

Edit: I did it with configurable memory allocation. I understand it is not good idea, as most OS manage memory for us, but my application was an ETL framework (intended to be used on server, but was also being used on desktop as a plugin for Adobe indesign). So, I was running in to issue of because instead of using swap, windows would return bad alloc and other applications start to fail. And as I was taught to avoid crashes and so, was just trying to degrade gracefully.

like image 403
theCakeCoder Avatar asked Mar 25 '10 06:03

theCakeCoder


People also ask

How do I get memory in C++?

In c++ you can get the memory address of a variable by using the & operator, like: cout << &i << endl; The output of that cout is the memory address of the first byte of the variable i we just created.

What is available system memory?

Available memory is the amount of memory that is available for allocation to new or existing processes. Available memory is then an estimation of how much memory is available for use without swapping.

What is available memory in free?

In the output of free , Free memory is the amount of memory which is currently not used for anything. This number should be small, because memory which is not used is simply wasted. Available memory is the amount of memory which is available for allocation to a new process or to existing processes.

How much memory free Linux?

Linux free -m1024 MB is the total system memory available, which would be physical RAM. 1 MB and 823 MB both show free because an application has access to both for memory storage.


1 Answers

On UNIX-like operating systems, there is sysconf.

#include <unistd.h>  unsigned long long getTotalSystemMemory() {     long pages = sysconf(_SC_PHYS_PAGES);     long page_size = sysconf(_SC_PAGE_SIZE);     return pages * page_size; } 

On Windows, there is GlobalMemoryStatusEx:

#include <windows.h>  unsigned long long getTotalSystemMemory() {     MEMORYSTATUSEX status;     status.dwLength = sizeof(status);     GlobalMemoryStatusEx(&status);     return status.ullTotalPhys; } 

So just do some fancy #ifdefs and you'll be good to go.

like image 112
Travis Gockel Avatar answered Oct 01 '22 14:10

Travis Gockel