From c4b2f313204c73a403ff9677a4d38c68581c5dd9 Mon Sep 17 00:00:00 2001 From: Dr-Noob Date: Wed, 9 Feb 2022 22:16:13 +0100 Subject: [PATCH] [v1.01] Read file in udev by dynamically reallocating a buffer, instead of allocating a fixed size. Should fix issue #137 --- src/common/global.c | 12 ++++++++++++ src/common/global.h | 1 + src/common/udev.c | 12 +++++++++--- src/common/udev.h | 1 - 4 files changed, 22 insertions(+), 4 deletions(-) diff --git a/src/common/global.c b/src/common/global.c index 47d4752..0545b2d 100644 --- a/src/common/global.c +++ b/src/common/global.c @@ -111,3 +111,15 @@ void* ecalloc(size_t nmemb, size_t size) { return ptr; } + +void* erealloc(void *ptr, size_t size) { + void* newptr = realloc(ptr, size); + + if(newptr == NULL) { + printErr("realloc failed: %s", strerror(errno)); + exit(1); + } + + return newptr; +} + diff --git a/src/common/global.h b/src/common/global.h index 3fa8688..5e5a0b3 100644 --- a/src/common/global.h +++ b/src/common/global.h @@ -15,5 +15,6 @@ int max(int a, int b); char *strremove(char *str, const char *sub); void* emalloc(size_t size); void* ecalloc(size_t nmemb, size_t size); +void* erealloc(void *ptr, size_t size); #endif diff --git a/src/common/udev.c b/src/common/udev.c index 75c60b2..395c637 100644 --- a/src/common/udev.c +++ b/src/common/udev.c @@ -55,11 +55,17 @@ char* read_file(char* path, int* len) { int bytes_read = 0; int offset = 0; int block = 128; - char* buf = emalloc(sizeof(char)*DEFAULT_FILE_SIZE); - memset(buf, 0, sizeof(char)*DEFAULT_FILE_SIZE); + int buf_size = block * 4; + char* buf = emalloc(sizeof(char) * buf_size); + memset(buf, 0, sizeof(char) * buf_size); - while ( (bytes_read = read(fd, buf+offset, block)) > 0 ) { + while ((bytes_read = read(fd, buf+offset, block)) > 0) { offset += bytes_read; + if(offset + block > buf_size) { + buf = erealloc(buf, sizeof(char) * buf_size * 2); + memset(buf + buf_size, 0, sizeof(char) * buf_size); + buf_size = buf_size * 2; + } } if (close(fd) == -1) { diff --git a/src/common/udev.h b/src/common/udev.h index b181b5f..ece967c 100644 --- a/src/common/udev.h +++ b/src/common/udev.h @@ -27,7 +27,6 @@ #define _PATH_FREQUENCY_MAX_LEN 100 #define _PATH_CACHE_MAX_LEN 200 -#define DEFAULT_FILE_SIZE 4096 char* read_file(char* path, int* len); long get_max_freq_from_file(uint32_t core);