]> Savannah Git Hosting - gnulib.git/commitdiff
reallocarray: Don't assume unportable behaviour of realloc.
authorBruno Haible <bruno@clisp.org>
Mon, 21 Oct 2024 15:20:37 +0000 (17:20 +0200)
committerBruno Haible <bruno@clisp.org>
Mon, 21 Oct 2024 15:20:37 +0000 (17:20 +0200)
* lib/reallocarray.c (reallocarray): Handle the nbytes==0 case
explicitly.
* modules/reallocarray (Depends-on): Remove realloc-gnu. Add
malloc-posix, realloc-posix.

ChangeLog
lib/reallocarray.c
modules/reallocarray

index 4e5e61b6548ea87dbc0e4bfd2fa883a9c2b61d3d..a9f4da95561779789402429fa859539dad8320d2 100644 (file)
--- a/ChangeLog
+++ b/ChangeLog
@@ -1,5 +1,11 @@
 2024-10-21  Bruno Haible  <bruno@clisp.org>
 
+       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
index 09711a0edeb3dd3870402b29408fea72fd35bace..e0377d087075b43f2aabd5e9566af38c0163972c 100644 (file)
@@ -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);
 }
index 380434870ee5d499099d3b09e4f7c96f7d94e6e1..dace5e636be2eded894a14167d07e9654b223567 100644 (file)
@@ -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