Home >Backend Development >C++ >How Can I Determine Available System Memory in C Across Different Platforms?
When dealing with memory-intensive applications, it is crucial to allocate buffers according to the available memory. This ensures that processing can proceed without exceeding memory limits and causing system instability. In a cross-platform environment, it is necessary to employ a platform-independent method to obtain available memory information.
Unix-Like Systems
Unix-like operating systems provide the sysconf function, which allows us to retrieve system configuration information. To obtain the total system memory, we can use:
#include <unistd.h> unsigned long long getTotalSystemMemory() { long pages = sysconf(_SC_PHYS_PAGES); long page_size = sysconf(_SC_PAGE_SIZE); return pages * page_size; }
Windows
On Windows, the GlobalMemoryStatusEx function can be used to retrieve memory information. The following code demonstrates how to use it:
#include <windows.h> unsigned long long getTotalSystemMemory() { MEMORYSTATUSEX status; status.dwLength = sizeof(status); GlobalMemoryStatusEx(&status); return status.ullTotalPhys; }
Cross-Platform Implementation
To create a cross-platform solution, we can use conditional compilation to select the appropriate function based on the operating system:
#ifdef __unix__ unsigned long long getTotalSystemMemory() { return sysconf(_SC_PHYS_PAGES) * sysconf(_SC_PAGE_SIZE); } #elif _WIN32 unsigned long long getTotalSystemMemory() { MEMORYSTATUSEX status; status.dwLength = sizeof(status); GlobalMemoryStatusEx(&status); return status.ullTotalPhys; } #endif
This will provide a consistent way to retrieve the available memory for your application on different operating systems.
The above is the detailed content of How Can I Determine Available System Memory in C Across Different Platforms?. For more information, please follow other related articles on the PHP Chinese website!