From: Bruno Haible Date: Mon, 21 Oct 2024 15:20:37 +0000 (+0200) Subject: reallocarray: Don't assume unportable behaviour of realloc. X-Git-Url: https://gitweb.git.savannah.gnu.org/gitweb/?a=commitdiff_plain;h=b3791b2bb9bdf03b2f99be5629d017a40382e1ee;p=gnulib.git reallocarray: Don't assume unportable behaviour of realloc. * lib/reallocarray.c (reallocarray): Handle the nbytes==0 case explicitly. * modules/reallocarray (Depends-on): Remove realloc-gnu. Add malloc-posix, realloc-posix. --- diff --git a/ChangeLog b/ChangeLog index 4e5e61b654..a9f4da9556 100644 --- a/ChangeLog +++ b/ChangeLog @@ -1,5 +1,11 @@ 2024-10-21 Bruno Haible + reallocarray: Don't assume unportable behaviour of realloc. + * lib/reallocarray.c (reallocarray): Handle the nbytes==0 case + explicitly. + * modules/reallocarray (Depends-on): Remove realloc-gnu. Add + malloc-posix, realloc-posix. + realloc: Optionally check for undefined behaviour. * m4/realloc.m4 (gl_FUNC_REALLOC_SANITIZED): New macro. (gl_FUNC_REALLOC_POSIX): Require it. If a sanitized realloc is diff --git a/lib/reallocarray.c b/lib/reallocarray.c index 09711a0ede..e0377d0870 100644 --- a/lib/reallocarray.c +++ b/lib/reallocarray.c @@ -33,6 +33,18 @@ reallocarray (void *ptr, size_t nmemb, size_t size) return NULL; } - /* Rely on the semantics of GNU realloc. */ + /* Avoid calling realloc (ptr, 0), since that is undefined behaviour in + ISO C 23 and since the GNU libc behaviour may possibly change. */ + if (nbytes == 0) + { + void *new_ptr = malloc (1); + if (new_ptr == NULL) + /* errno is set here. */ + return NULL; + free (ptr); + return new_ptr; + } + + /* Call realloc, setting errno to ENOMEM on failure. */ return realloc (ptr, nbytes); } diff --git a/modules/reallocarray b/modules/reallocarray index 380434870e..dace5e636b 100644 --- a/modules/reallocarray +++ b/modules/reallocarray @@ -8,7 +8,8 @@ m4/reallocarray.m4 Depends-on: extensions -realloc-gnu [test $HAVE_REALLOCARRAY = 0 || test $REPLACE_REALLOCARRAY = 1] +malloc-posix [test $HAVE_REALLOCARRAY = 0 || test $REPLACE_REALLOCARRAY = 1] +realloc-posix [test $HAVE_REALLOCARRAY = 0 || test $REPLACE_REALLOCARRAY = 1] stdckdint [test $HAVE_REALLOCARRAY = 0 || test $REPLACE_REALLOCARRAY = 1] stdlib