From fce0c31c86f32fbbd6be32970931af1047488484 Mon Sep 17 00:00:00 2001 From: John Lindgren Date: Sat, 23 Mar 2024 15:34:13 -0400 Subject: [PATCH] Optional better C stdlib integration - Optionally set errno to ENOMEM when out of memory - Optionally use memset() to implement memclear() - Optionally use memcpy() to implement memcopy() --- tinyalloc.c | 34 +++++++++++++++++++++++++++------- 1 file changed, 27 insertions(+), 7 deletions(-) diff --git a/tinyalloc.c b/tinyalloc.c index 9fecf50..96f02d3 100644 --- a/tinyalloc.c +++ b/tinyalloc.c @@ -9,6 +9,12 @@ extern void print_i(size_t); #define print_i(X) #endif +/* optional C stdlib integration */ +#ifdef TA_USE_STDLIB +#include +#include +#endif + typedef struct Block Block; struct Block { @@ -227,9 +233,16 @@ void *ta_alloc(size_t num) { if (block != NULL) { return block->addr; } +#ifdef TA_USE_STDLIB + errno = ENOMEM; +#endif return NULL; } +#ifdef TA_USE_STDLIB +#define memclear(ptr, num) memset((ptr), 0, (num)) +#define memcopy(dst, src, num) memcpy((dst), (src), (num)) +#else static void memclear(void *ptr, size_t num) { size_t *ptrw = (size_t *)ptr; size_t numw = (num & -sizeof(size_t)) / sizeof(size_t); @@ -257,18 +270,22 @@ static void memcopy(void *dst, void *src, size_t num) { *dstb++ = *srcb++; } } +#endif void *ta_calloc(size_t num, size_t size) { size_t orig = num; num *= size; - if (size != 0 && num / size != orig) { - return NULL; // overflow - } - Block *block = alloc_block(num); - if (block != NULL) { - memclear(block->addr, block->size); - return block->addr; + // check for overflow + if (size == 0 || num / size == orig) { + Block *block = alloc_block(num); + if (block != NULL) { + memclear(block->addr, block->size); + return block->addr; + } } +#ifdef TA_USE_STDLIB + errno = ENOMEM; +#endif return NULL; } @@ -306,6 +323,9 @@ void *ta_realloc(void *ptr, size_t num) { ta_free(ptr); return block->addr; } +#ifdef TA_USE_STDLIB + errno = ENOMEM; +#endif return NULL; }