From: Alejandro Colomar Date: Sun, 30 Jul 2023 12:29:45 +0000 (+0200) Subject: sizeof.h: Add SIZEOF_ARRAY() macro X-Git-Tag: 4.15.0-rc1~207 X-Git-Url: http://git.ipfire.org/cgi-bin/gitweb.cgi?a=commitdiff_plain;h=e29994218960382fea8854d58e44af3b5a405f94;p=thirdparty%2Fshadow.git sizeof.h: Add SIZEOF_ARRAY() macro 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 --- diff --git a/lib/sizeof.h b/lib/sizeof.h index 0ee0667a1..f16e1a7bf 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