Added the new mallocWithFallback function which tries to allocate the specified size and falls back to a smaller size when fails

This commit is contained in:
Th3maz1ng 2022-04-23 22:51:52 +02:00
parent d9dfc15f21
commit 4635f4daaa
2 changed files with 18 additions and 0 deletions

View File

@ -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;
}

View File

@ -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