0 0 0 0


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.

Best Answer:

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()
    status.dwLength = sizeof(status);
    return status.ullTotalPhys;

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

And so that I don't get marked down a others have said, you should not take up all the space available and there are probably better ways to do what you actually want to do. This technique doesn't actually get you the same definition of amount of memory, since some operating systems will use "pages" to mean whatever the hell they want (disk buffers, I/O devices). There is a huge disconnect between the memory space you have access to and the physical bytes in RAM (look up the translation lookaside buffer for just one example of this).

Copyright © 2011 Dowemo All rights reserved.    Creative Commons   AboutUs