From 4635f4daaa2107329c2f22ea7587b5558cbe81ba Mon Sep 17 00:00:00 2001 From: Th3maz1ng Date: Sat, 23 Apr 2022 22:51:52 +0200 Subject: [PATCH] Added the new mallocWithFallback function which tries to allocate the specified size and falls back to a smaller size when fails --- src/app/utilities.cpp | 17 +++++++++++++++++ src/app/utilities.h | 1 + 2 files changed, 18 insertions(+) diff --git a/src/app/utilities.cpp b/src/app/utilities.cpp index 3eed40a..8543e3b 100644 --- a/src/app/utilities.cpp +++ b/src/app/utilities.cpp @@ -68,3 +68,20 @@ uint32_t monthNumTo3LetterAbbreviation(const uint8_t monthNumber) return toReturn; } + +void *mallocWithFallback(size_t requestedSize, size_t *acceptedSize) +{ + void *allocAddr(nullptr); + uint32_t divider(1); + + do + { + requestedSize /= divider++; + allocAddr = malloc(requestedSize); + } while(!allocAddr && requestedSize >= 50); //If we can't even manage to malloc 50 bytes then we should give up and cry + + if(acceptedSize && allocAddr)*acceptedSize = requestedSize; + else if(acceptedSize)*acceptedSize = 0; + + return allocAddr; +} \ No newline at end of file diff --git a/src/app/utilities.h b/src/app/utilities.h index f429317..19de3ff 100644 --- a/src/app/utilities.h +++ b/src/app/utilities.h @@ -5,4 +5,5 @@ char *addChar(char *pointer, const char character); char *dateTimeFormater(char *pointer, const uint8_t value, const char character); uint32_t monthNumTo3LetterAbbreviation(const uint8_t monthNumber); +void *mallocWithFallback(size_t requestedSize, size_t *acceptedSize = nullptr); #endif // UTILITIES_H