From 94dc4821bac1877209f2cd1354dda8ea7c1868fc Mon Sep 17 00:00:00 2001 From: Dorian Zedler Date: Sat, 23 Jul 2022 18:06:25 +0200 Subject: [PATCH] Fix: include cached ram in calculation --- Implementierung/src/io.c | 24 +++++++++++++++++++++--- 1 file changed, 21 insertions(+), 3 deletions(-) diff --git a/Implementierung/src/io.c b/Implementierung/src/io.c index 3f1acbb..3ee2ada 100644 --- a/Implementierung/src/io.c +++ b/Implementierung/src/io.c @@ -24,6 +24,25 @@ bool open_file(const char* path, FILE** file, struct stat* file_stat) { return true; } +unsigned long get_available_memory() { + FILE* f; + struct stat statOfFile; + if (!open_file("/proc/meminfo", &f, &statOfFile)) { + return 0; + } + + char line[100]; + while (fgets(line, sizeof(line), f)) { + unsigned long available_memory; + if (sscanf(line, "MemAvailable: %ld kB", &available_memory) == 1) { + fclose(f); + return available_memory * 1000; + } + } + + return 0; +} + uint8_t* read_file(const char* path, size_t* size) { // Read the contents of the file specified by path into a heap-allocated // buffer and return a pointer to that buffer. @@ -33,10 +52,9 @@ uint8_t* read_file(const char* path, size_t* size) { return NULL; } - struct sysinfo info; - int r = sysinfo(&info); + unsigned long available_memory = get_available_memory(); - if (r != 0 || info.freeram < (unsigned long)(statOfFile.st_size * 2)) { + if (available_memory < (unsigned long)(statOfFile.st_size * 2)) { errno = ENOMEM; return NULL; }