Skip to content

Commit

Permalink
Optional better C stdlib integration
Browse files Browse the repository at this point in the history
- Optionally set errno to ENOMEM when out of memory
- Optionally use memset() to implement memclear()
- Optionally use memcpy() to implement memcopy()
  • Loading branch information
jlindgren90 committed Mar 25, 2024
1 parent 44c4678 commit fce0c31
Showing 1 changed file with 27 additions and 7 deletions.
34 changes: 27 additions & 7 deletions tinyalloc.c
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,12 @@ extern void print_i(size_t);
#define print_i(X)
#endif

/* optional C stdlib integration */
#ifdef TA_USE_STDLIB
#include <errno.h>
#include <string.h>
#endif

typedef struct Block Block;

struct Block {
Expand Down Expand Up @@ -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);
Expand Down Expand Up @@ -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;
}

Expand Down Expand Up @@ -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;
}

Expand Down

0 comments on commit fce0c31

Please sign in to comment.