Sobes.tech
Junior — Middle

How can a programmer determine the amount of available RAM during program execution?

sobes.tech AI

Answer from AI

The amount of available RAM during program execution can be determined in different ways depending on the OS.

For Linux, you can read information from the /proc/meminfo file or use system calls:

#include <sys/sysinfo.h>

struct sysinfo info;
if (sysinfo(&info) == 0) {
    unsigned long total_ram = info.totalram * info.mem_unit;
    unsigned long free_ram = info.freeram * info.mem_unit;
    // total_ram and free_ram are in bytes
}

For Windows, you can use the GlobalMemoryStatusEx function:

#include <windows.h>

MEMORYSTATUSEX statex;
statex.dwLength = sizeof(statex);
GlobalMemoryStatusEx(&statex);

DWORDLONG total_ram = statex.ullTotalPhys;
DWORDLONG free_ram = statex.ullAvailPhys;

Thus, a programmer can dynamically obtain information about available memory and adapt the program's behavior accordingly.