Home >Backend Development >C++ >How Can I Retrieve Available System Memory in C Across Different Platforms?
In scenarios where memory allocation must adapt to available system resources, there is a need to determine the amount of memory available to an application at runtime. This article explores methods for platform-independent retrieval of available memory on Windows, macOS, Linux, and AIX.
The sysconf function provides a standardized way to obtain system configuration parameters, including memory information. The code below uses sysconf to query the total physical memory:
#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, the GlobalMemoryStatusEx function provides detailed information about memory usage, including total physical memory:
#include <windows.h> unsigned long long getTotalSystemMemory() { MEMORYSTATUSEX status; status.dwLength = sizeof(status); GlobalMemoryStatusEx(&status); return status.ullTotalPhys; }
To use this information in your application, you can define a cross-platform function that returns the available memory:
#ifdef WIN32 unsigned long long getTotalSystemMemory() { return GlobalMemoryStatusEx(); } #else unsigned long long getTotalSystemMemory() { return sysconf(_SC_PHYS_PAGES) * sysconf(_SC_PAGE_SIZE); } #endif
Then, you can allocate buffers based on the available memory:
void allocateBuffers() { unsigned long long availableMemory = getTotalSystemMemory(); // Allocate buffers according to `availableMemory` }
Note that the concept of virtual versus physical memory may vary between platforms and operating systems, so it is essential to use the correct functions for each target system.
The above is the detailed content of How Can I Retrieve Available System Memory in C Across Different Platforms?. For more information, please follow other related articles on the PHP Chinese website!