1
0
mirror of https://git.savannah.gnu.org/git/gnulib.git synced 2025-08-08 17:22:05 +03:00

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.
This commit is contained in:
Bruno Haible
2024-10-21 17:20:37 +02:00
parent 12cd6eca20
commit b3791b2bb9
3 changed files with 21 additions and 2 deletions

View File

@@ -1,5 +1,11 @@
2024-10-21 Bruno Haible <bruno@clisp.org> 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. realloc: Optionally check for undefined behaviour.
* m4/realloc.m4 (gl_FUNC_REALLOC_SANITIZED): New macro. * m4/realloc.m4 (gl_FUNC_REALLOC_SANITIZED): New macro.
(gl_FUNC_REALLOC_POSIX): Require it. If a sanitized realloc is (gl_FUNC_REALLOC_POSIX): Require it. If a sanitized realloc is

View File

@@ -33,6 +33,18 @@ reallocarray (void *ptr, size_t nmemb, size_t size)
return NULL; 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); return realloc (ptr, nbytes);
} }

View File

@@ -8,7 +8,8 @@ m4/reallocarray.m4
Depends-on: Depends-on:
extensions 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] stdckdint [test $HAVE_REALLOCARRAY = 0 || test $REPLACE_REALLOCARRAY = 1]
stdlib stdlib