Skip to content

Commit

Permalink
[libc] calloc must check for overflow (C99)
Browse files Browse the repository at this point in the history
I think this was first standardized in C99, but was commonly checked for
earlier than that.
  • Loading branch information
ccoffing committed Dec 8, 2023
1 parent d3b43f9 commit 58fa2b7
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 4 deletions.
4 changes: 3 additions & 1 deletion elkscmd/test/libc/malloc.c
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,9 @@ TEST_CASE(malloc_calloc) {
free(p);
}

/* TODO check for mult overflow */
p = calloc(((unsigned)-1)>>2, 5);
EXPECT_EQ(errno, ENOMEM);
EXPECT_EQ_P(p, NULL);
}

TEST_CASE(malloc_realloc) {
Expand Down
20 changes: 17 additions & 3 deletions libc/malloc/calloc.c
Original file line number Diff line number Diff line change
@@ -1,13 +1,27 @@
#include <errno.h>
#include <malloc.h>
#include <string.h>

void *
calloc(unsigned int elm, unsigned int sz)
{
register unsigned int v;
register void *ptr;
unsigned int v;
void *ptr;

ptr = malloc(v = elm * sz);
#ifdef __GNUC__
if (__builtin_umul_overflow(elm, sz, &v)) {
errno = ENOMEM;
return 0;
}
#else
v = elm * sz;
if (sz != 0 && v / sz != elm) {
errno = ENOMEM;
return 0;
}
#endif

ptr = malloc(v);
if (ptr)
memset(ptr, 0, v);

Expand Down

0 comments on commit 58fa2b7

Please sign in to comment.