From afc4b574b7372e72cffb695214bc08e1a6a86a75 Mon Sep 17 00:00:00 2001 From: Alejandro Colomar Date: Wed, 16 Oct 2024 20:31:25 +0200 Subject: [PATCH] lib/alloc/realloc*.h: Always reallocate at least 1 byte MIME-Version: 1.0 Content-Type: text/plain; charset=utf8 Content-Transfer-Encoding: 8bit glibc's realloc(3) is broken. It was originally good (I believe) until at some point, when it was changed to conform to C89, which had a bogus specification that required that it returns NULL. C99 fixed the mistake from C89, and so glibc's realloc(3) is non-conforming to C99/C11/POSIX.1-2008. C17 broke again the definition of realloc(3). Link: Link: Link: Co-developed-by: наб Signed-off-by: наб Reviewed-by: Iker Pedrosa Acked-by: Paul Eggert Signed-off-by: Alejandro Colomar --- lib/alloc/realloc.h | 2 +- lib/alloc/reallocf.h | 7 +++---- 2 files changed, 4 insertions(+), 5 deletions(-) diff --git a/lib/alloc/realloc.h b/lib/alloc/realloc.h index fd31ab89e..63f14dc2e 100644 --- a/lib/alloc/realloc.h +++ b/lib/alloc/realloc.h @@ -13,7 +13,7 @@ #define REALLOC(p, n, type) \ ( \ - _Generic(p, type *: (type *) reallocarray(p, n, sizeof(type))) \ + _Generic(p, type *: (type *) reallocarray(p, (n) ?: 1, sizeof(type))) \ ) diff --git a/lib/alloc/reallocf.h b/lib/alloc/reallocf.h index 5854330aa..2d328b6a4 100644 --- a/lib/alloc/reallocf.h +++ b/lib/alloc/reallocf.h @@ -16,7 +16,7 @@ #define REALLOCF(p, n, type) \ ( \ - _Generic(p, type *: (type *) reallocarrayf(p, n, sizeof(type))) \ + _Generic(p, type *: (type *) reallocarrayf(p, (n) ?: 1, sizeof(type)))\ ) @@ -30,10 +30,9 @@ reallocarrayf(void *p, size_t nmemb, size_t size) { void *q; - q = reallocarray(p, nmemb, size); + q = reallocarray(p, nmemb ?: 1, size ?: 1); - /* realloc(p, 0) is equivalent to free(p); avoid double free. */ - if (q == NULL && nmemb != 0 && size != 0) + if (q == NULL) free(p); return q; } -- 2.47.2