#include <cstdio> // For snprintf, fopen, fclose, fgets, sscanf
#include <cstring> // For strcmp, strlen
#include <cstdint> // For uint64_t
#include <cmath> // For fmod, used in percentage calculation
// --- Platform-specific headers ---
#ifdef _WIN32
#include <windows.h>
#elif defined(__linux__)
// No specific Linux headers needed beyond C standard library for /proc/meminfo
#elif defined(__APPLE__)
#include <sys/sysctl.h>
#include <mach/mach.h>
#include <stdio.h> // For perror
#endif
// --- End Platform-specific headers ---
// --- Configuration for static buffers ---
// Max length for a formatted byte string (e.g., "999.99 GB\0")
#define MAX_FORMATTED_BYTES_LEN 32
// Max length for a single line from /proc/meminfo or similar.
#define MAX_LINE_LEN 256
// Max length for a key from /proc/meminfo (e.g., "MemTotal:\0")
#define MAX_KEY_LEN 64
// Overall output buffer size (generous estimate)
// Calculate roughly: (3 lines fixed + 6 lines variable) * ~50 chars/line + header
// ~300 chars. Let's make it more robust.
#define MAX_OUTPUT_STRING_LEN 1024
// --- End Configuration ---
// Helper struct to hold memory info
struct SystemMemoryInfo {
uint64_t totalPhysicalBytes;
uint64_t availablePhysicalBytes;
uint64_t totalVirtualBytes;
uint64_t availableVirtualBytes;
// Default constructor to initialize
SystemMemoryInfo() :
totalPhysicalBytes(0), availablePhysicalBytes(0),
totalVirtualBytes(0), availableVirtualBytes(0) {}
};
// Helper function to format bytes into human-readable string
// Writes directly into the provided buffer.
// Returns a pointer to the buffer.
void formatBytes(uint64_t bytes, char* buffer, size_t buffer_size) {
const int KB = 1024;
const int MB = KB * 1024;
const uint64_t GB = (uint64_t)MB * 1024;
double val;
const char* unit;
if (bytes >= GB) {
val = (double)bytes / GB;
unit = "GB";
} else if (bytes >= MB) {
val = (double)bytes / MB;
unit = "MB";
} else if (bytes >= KB) {
val = (double)bytes / KB;
unit = "KB";
} else {
val = (double)bytes;
unit = "Bytes";
}
snprintf(buffer, buffer_size, "%.2f %s", val, unit);
}
// Function to get memory information (platform-specific implementation)
bool getSystemMemoryInfo(SystemMemoryInfo& info) {
#ifdef _WIN32
MEMORYSTATUSEX statex;
statex.dwLength = sizeof(statex);
if (GlobalMemoryStatusEx(&statex)) {
info.totalPhysicalBytes = statex.ullTotalPhys;
info.availablePhysicalBytes = statex.ullAvailPhys;
info.totalVirtualBytes = statex.ullTotalVirtual;
info.availableVirtualBytes = statex.ullAvailVirtual;
return true;
}
return false;
#elif defined(__linux__)
FILE* file = fopen("/proc/meminfo", "r");
if (!file) {
return false;
}
char line[MAX_LINE_LEN];
uint64_t memTotal = 0, memAvailable = 0, swapTotal = 0, swapFree = 0;
while (fgets(line, sizeof(line), file)) {
char key[MAX_KEY_LEN];
uint64_t value;
char unit[8]; // e.g., "kB"
if (sscanf(line, "%s %llu %s", key, &value, unit) == 3) {
// Remove trailing colon from key if present
size_t key_len = strlen(key);
if (key_len > 0 && key[key_len - 1] == ':') {
key[key_len - 1] = '\0';
}
// Values in /proc/meminfo are typically in KB, convert to bytes
if (strcmp(key, "MemTotal") == 0) {
memTotal = value * 1024ULL;
} else if (strcmp(key, "MemAvailable") == 0) { // Prefer MemAvailable for 'available'
memAvailable = value * 1024ULL;
} else if (strcmp(key, "SwapTotal") == 0) {
swapTotal = value * 1024ULL;
} else if (strcmp(key, "SwapFree") == 0) {
swapFree = value * 1024ULL;
}
}
}
fclose(file);
info.totalPhysicalBytes = memTotal;
info.availablePhysicalBytes = memAvailable;
info.totalVirtualBytes = memTotal + swapTotal;
info.availableVirtualBytes = memAvailable + swapFree;
return true;
#elif defined(__APPLE__)
int mib[2];
size_t len;
// Total Physical Memory
mib[0] = CTL_HW;
mib[1] = HW_MEMSIZE;
len = sizeof(info.totalPhysicalBytes);
sysctl(mib, 2, &info.totalPhysicalBytes, &len, NULL, 0);
// Available Physical Memory (more complex on macOS, often uses vm_stat)
// This is an approximation based on free, inactive, speculative pages
vm_statistics64_data_t vmStats;
mach_msg_type_number_t count = sizeof(vmStats) / sizeof(natural_t);
if (KERN_SUCCESS == host_statistics64(mach_host_self(), HOST_VM_INFO64, (host_info_t)&vmStats, &count)) {
uint64_t pageSize = 0;
len = sizeof(pageSize);
mib[0] = CTL_VM;
mib[1] = VM_PAGESIZE;
sysctl(mib, 2, &pageSize, &len, NULL, 0);
// Sum of free, inactive, speculative pages usually represents available
info.availablePhysicalBytes = (vmStats.free_count + vmStats.inactive_count + vmStats.speculative_count) * pageSize;
} else {
info.availablePhysicalBytes = 0; // Or handle error
// fprintf(stderr, "Error: host_statistics64 failed.\n"); // For debugging
}
// Swap Memory
xsw_usage swap_usage;
mib[0] = CTL_VM;
mib[1] = VM_SWAPUSAGE;
len = sizeof(swap_usage);
if (sysctl(mib, 2, &swap_usage, &len, NULL, 0) == 0) {
uint64_t totalSwap = swap_usage.xsu_total;
uint64_t usedSwap = swap_usage.xsu_used;
uint64_t freeSwap = totalSwap - usedSwap;
info.totalVirtualBytes = info.totalPhysicalBytes + totalSwap;
info.availableVirtualBytes = info.availablePhysicalBytes + freeSwap;
} else {
// If swap info fails, virtual memory is just physical memory
info.totalVirtualBytes = info.totalPhysicalBytes;
info.availableVirtualBytes = info.availablePhysicalBytes;
// perror("sysctl VM_SWAPUSAGE"); // For debugging
}
return true;
#else
// Unsupported OS
return false;
#endif
}
// Global static buffer for the output string.
// This means the returned pointer will always point to this same buffer.
// Subsequent calls will overwrite the content.
static char s_output_buffer[MAX_OUTPUT_STRING_LEN];
// Main function to get formatted memory string
// Returns a const char* pointer to a static buffer.
const char* getMemoryInfoString() {
SystemMemoryInfo info;
// Pointer to current position in the output buffer
char* current_ptr = s_output_buffer;
// Remaining size in the output buffer
size_t remaining_size = sizeof(s_output_buffer);
int written = 0; // Number of characters written by snprintf
// Buffer for formatted byte strings (e.g., "1.23 GB")
char formatted_bytes_buffer[MAX_FORMATTED_BYTES_LEN];
if (getSystemMemoryInfo(info)) {
// Calculate percentages
double physOccupiedPct = 0.0;
if (info.totalPhysicalBytes > 0) {
physOccupiedPct = (double)(info.totalPhysicalBytes - info.availablePhysicalBytes) / info.totalPhysicalBytes * 100.0;
}
double virtOccupiedPct = 0.0;
if (info.totalVirtualBytes > 0) {
virtOccupiedPct = (double)(info.totalVirtualBytes - info.availableVirtualBytes) / info.totalVirtualBytes * 100.0;
}
// Build the output string using snprintf
written = snprintf(current_ptr, remaining_size, "--- System Memory Information ---\n");
if (written < 0 || (size_t)written >= remaining_size) { // Error or truncation
return "Error: Output buffer too small.";
}
current_ptr += written;
remaining_size -= written;
written = snprintf(current_ptr, remaining_size, "Physical Memory (RAM):\n");
if (written < 0 || (size_t)written >= remaining_size) { return s_output_buffer; }
current_ptr += written;
remaining_size -= written;
formatBytes(info.totalPhysicalBytes, formatted_bytes_buffer, sizeof(formatted_bytes_buffer));
written = snprintf(current_ptr, remaining_size, " Total: %s\n", formatted_bytes_buffer);
if (written < 0 || (size_t)written >= remaining_size) { return s_output_buffer; }
current_ptr += written;
remaining_size -= written;
formatBytes(info.availablePhysicalBytes, formatted_bytes_buffer, sizeof(formatted_bytes_buffer));
written = snprintf(current_ptr, remaining_size, " Available: %s\n", formatted_bytes_buffer);
if (written < 0 || (size_t)written >= remaining_size) { return s_output_buffer; }
current_ptr += written;
remaining_size -= written;
written = snprintf(current_ptr, remaining_size, " Occupied: %.2f%%\n\n", physOccupiedPct);
if (written < 0 || (size_t)written >= remaining_size) { return s_output_buffer; }
current_ptr += written;
remaining_size -= written;
written = snprintf(current_ptr, remaining_size, "Virtual Memory (RAM + Swap):\n");
if (written < 0 || (size_t)written >= remaining_size) { return s_output_buffer; }
current_ptr += written;
remaining_size -= written;
formatBytes(info.totalVirtualBytes, formatted_bytes_buffer, sizeof(formatted_bytes_buffer));
written = snprintf(current_ptr, remaining_size, " Total: %s\n", formatted_bytes_buffer);
if (written < 0 || (size_t)written >= remaining_size) { return s_output_buffer; }
current_ptr += written;
remaining_size -= written;
formatBytes(info.availableVirtualBytes, formatted_bytes_buffer, sizeof(formatted_bytes_buffer));
written = snprintf(current_ptr, remaining_size, " Available: %s\n", formatted_bytes_buffer);
if (written < 0 || (size_t)written >= remaining_size) { return s_output_buffer; }
current_ptr += written;
remaining_size -= written;
written = snprintf(current_ptr, remaining_size, " Occupied: %.2f%%", virtOccupiedPct);
if (written < 0 || (size_t)written >= remaining_size) { return s_output_buffer; }
// No need to adjust current_ptr/remaining_size after the last snprintf if it's the very end.
} else {
snprintf(s_output_buffer, sizeof(s_output_buffer), "Error: Could not retrieve system memory information for this OS.\n");
#ifndef _WIN32
#ifndef __linux__
#ifndef __APPLE__
strncat(s_output_buffer, "This program currently supports Windows, Linux, and macOS.\n",
sizeof(s_output_buffer) - strlen(s_output_buffer) -1);
#endif
#endif
#endif
}
return s_output_buffer;
}
int main() {
// The getMemoryInfoString() function returns a pointer to a static buffer.
// No new memory is allocated here.
const char* memory_info = getMemoryInfoString();
printf("%s\n", memory_info); // Using printf for C-style string output
return 0;
}