Home >Backend Development >C++ >How Can I Retrieve Available System Memory in C Across Different Platforms?

How Can I Retrieve Available System Memory in C Across Different Platforms?

Barbara Streisand
Barbara StreisandOriginal
2024-12-30 13:16:15581browse

How Can I Retrieve Available System Memory in C   Across Different Platforms?

Retrieving Available Memory in C /g

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.

UNIX-Like Systems (Linux, macOS, 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;
}

Windows

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;
}

Usage

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn