aboutsummaryrefslogtreecommitdiff
path: root/lib/libc/stdlib
diff options
context:
space:
mode:
authorRobert Clausecker <fuz@FreeBSD.org>2025-10-02 13:26:46 +0000
committerRobert Clausecker <fuz@FreeBSD.org>2025-10-03 17:45:54 +0000
commit7233893e949689d378d38c11651e68321deed12c (patch)
treeecb5de2ce231ba1af70ec88a5ac8918b0b2613b5 /lib/libc/stdlib
parenta8d774d9708c100a52f231065d9d5f1b4c3aceb7 (diff)
lib{c,openbsd}: use ckd_mul() for overflow checking in re(c)allocarray
Summary: This makes the code easier to understand and slightly faster, but requires C23. calloc() would benefit, too, but I didn't want to touch the imported jemalloc code base. Reviewed by: kib Differential Revision: https://reviews.freebsd.org/D52854
Diffstat (limited to 'lib/libc/stdlib')
-rw-r--r--lib/libc/stdlib/reallocarray.c14
1 files changed, 5 insertions, 9 deletions
diff --git a/lib/libc/stdlib/reallocarray.c b/lib/libc/stdlib/reallocarray.c
index 0868804486cc..3632734c84de 100644
--- a/lib/libc/stdlib/reallocarray.c
+++ b/lib/libc/stdlib/reallocarray.c
@@ -17,23 +17,19 @@
#include <sys/types.h>
#include <errno.h>
+#include <stdckdint.h>
#include <stdint.h>
#include <stdlib.h>
-/*
- * This is sqrt(SIZE_MAX+1), as s1*s2 <= SIZE_MAX
- * if both s1 < MUL_NO_OVERFLOW and s2 < MUL_NO_OVERFLOW
- */
-#define MUL_NO_OVERFLOW ((size_t)1 << (sizeof(size_t) * 4))
-
void *
reallocarray(void *optr, size_t nmemb, size_t size)
{
+ size_t nbytes;
- if ((nmemb >= MUL_NO_OVERFLOW || size >= MUL_NO_OVERFLOW) &&
- nmemb > 0 && SIZE_MAX / nmemb < size) {
+ if (ckd_mul(&nbytes, nmemb, size)) {
errno = ENOMEM;
return (NULL);
}
- return (realloc(optr, size * nmemb));
+
+ return (realloc(optr, nbytes));
}