From e29994218960382fea8854d58e44af3b5a405f94 Mon Sep 17 00:00:00 2001 From: Alejandro Colomar Date: Sun, 30 Jul 2023 14:29:45 +0200 Subject: [PATCH] sizeof.h: Add SIZEOF_ARRAY() macro MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit This makes it safe to call sizeof() on an array. Calling sizeof() directly on an array is dangerous, because if the array changes to be a pointer, the behavior will unexpectedly change. It's the same problem as with NITEMS(). Link: Cc: Christian Göttsche Cc: Serge Hallyn Cc: Iker Pedrosa Signed-off-by: Alejandro Colomar --- lib/sizeof.h | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/lib/sizeof.h b/lib/sizeof.h index 0ee0667a..f16e1a7b 100644 --- a/lib/sizeof.h +++ b/lib/sizeof.h @@ -15,9 +15,10 @@ #include "must_be.h" -#define WIDTHOF(x) (sizeof(x) * CHAR_BIT) -#define NITEMS(a) (sizeof((a)) / sizeof((a)[0]) + must_be_array(a)) -#define STRLEN(s) (NITEMS(s) - 1) +#define WIDTHOF(x) (sizeof(x) * CHAR_BIT) +#define SIZEOF_ARRAY(a) (sizeof(a) + must_be_array(a)) +#define NITEMS(a) (SIZEOF_ARRAY((a)) / sizeof((a)[0])) +#define STRLEN(s) (NITEMS(s) - 1) #endif // include guard