* lib/reallocarray.c (reallocarray): Handle the nbytes==0 case
explicitly.
* modules/reallocarray (Depends-on): Remove realloc-gnu. Add
malloc-posix, realloc-posix.
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
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);
}
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