diff options
| author | Craig Barnes <craigbarnes@protonmail.com> | 2026-07-13 10:48:52 +0000 |
|---|---|---|
| committer | Daniel Eklöf <daniel@ekloef.se> | 2026-07-21 09:00:52 +0000 |
| commit | da7bdf8ab7dc999009b6b83d3354066c18ec4f38 (patch) | |
| tree | 1b2a6f33a3b5547f4e8d3f51558d09298cf53bee /xmalloc.c | |
| parent | config: add ferra theme (diff) | |
xmalloc: avoid using reallocarray(3) to implement xreallocarray()
See the added comment for reasoning.
The reallocarray(3) function in libc could have been used conditionally,
when available, but since it can be implemented simply and efficiently,
the portable version may just as well be used in all cases.
See also:
* https://pubs.opengroup.org/onlinepubs/9799919799/functions/reallocarray.html#:~:text=adding-,reallocarray
* https://android.googlesource.com/platform/bionic/+/HEAD/docs/status.md#:~:text=reallocarray
* https://github.com/termux/termux-packages/tree/26826aec834182c/x11-packages/foot
* https://github.com/termux/termux-packages/blob/26826aec834182c/x11-packages/foot/reallocarray.c#L6
* https://github.com/termux/termux-packages/blob/26826aec834182c/x11-packages/foot/xmalloc.c.patch#L7
* https://github.com/termux/termux-packages/pull/17818
* https://github.com/termux/termux-packages/issues/23833 (see expanded build log)
Diffstat (limited to 'xmalloc.c')
| -rw-r--r-- | xmalloc.c | 15 |
1 files changed, 9 insertions, 6 deletions
@@ -1,4 +1,5 @@ #include <errno.h> +#include <stdint.h> #include <stdio.h> #include <stdlib.h> #include "xmalloc.h" @@ -33,16 +34,18 @@ void * xrealloc(void *ptr, size_t size) { xassert(size != 0); - void *alloc = realloc(ptr, size); - return check_alloc(alloc); + return check_alloc(realloc(ptr, size)); } +// reallocarray(3) was only added to POSIX in Issue 8 (2024) and isn't +// present on some platforms (e.g. Android API levels < 29), so this +// function is both for portability and ENOMEM handling. void * -xreallocarray(void *ptr, size_t n, size_t size) +xreallocarray(void *ptr, size_t nmemb, size_t size) { - xassert(n != 0 && size != 0); - void *alloc = reallocarray(ptr, n, size); - return check_alloc(alloc); + FATAL_ERROR_ON(nmemb == 0 || size == 0, EINVAL); + FATAL_ERROR_ON(size > SIZE_MAX / nmemb, EOVERFLOW); + return xrealloc(ptr, nmemb * size); } char * |
