[v1.01] Read file in udev by dynamically reallocating a buffer, instead of allocating a fixed size. Should fix issue #137

This commit is contained in:
Dr-Noob
2022-02-09 22:16:13 +01:00
parent 3046e84b4b
commit c4b2f31320
4 changed files with 22 additions and 4 deletions

View File

@@ -111,3 +111,15 @@ void* ecalloc(size_t nmemb, size_t size) {
return ptr; 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;
}

View File

@@ -15,5 +15,6 @@ int max(int a, int b);
char *strremove(char *str, const char *sub); char *strremove(char *str, const char *sub);
void* emalloc(size_t size); void* emalloc(size_t size);
void* ecalloc(size_t nmemb, size_t size); void* ecalloc(size_t nmemb, size_t size);
void* erealloc(void *ptr, size_t size);
#endif #endif

View File

@@ -55,11 +55,17 @@ char* read_file(char* path, int* len) {
int bytes_read = 0; int bytes_read = 0;
int offset = 0; int offset = 0;
int block = 128; int block = 128;
char* buf = emalloc(sizeof(char)*DEFAULT_FILE_SIZE); int buf_size = block * 4;
memset(buf, 0, sizeof(char)*DEFAULT_FILE_SIZE); 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; 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) { if (close(fd) == -1) {

View File

@@ -27,7 +27,6 @@
#define _PATH_FREQUENCY_MAX_LEN 100 #define _PATH_FREQUENCY_MAX_LEN 100
#define _PATH_CACHE_MAX_LEN 200 #define _PATH_CACHE_MAX_LEN 200
#define DEFAULT_FILE_SIZE 4096
char* read_file(char* path, int* len); char* read_file(char* path, int* len);
long get_max_freq_from_file(uint32_t core); long get_max_freq_from_file(uint32_t core);