]> git.ipfire.org Git - thirdparty/shadow.git/commitdiff
sizeof.h: Add SIZEOF_ARRAY() macro
authorAlejandro Colomar <alx@kernel.org>
Sun, 30 Jul 2023 12:29:45 +0000 (14:29 +0200)
committerIker Pedrosa <ikerpedrosam@gmail.com>
Fri, 1 Sep 2023 07:39:23 +0000 (09:39 +0200)
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: <https://stackoverflow.com/a/57537491>
Cc: Christian Göttsche <cgzones@googlemail.com>
Cc: Serge Hallyn <serge@hallyn.com>
Cc: Iker Pedrosa <ipedrosa@redhat.com>
Signed-off-by: Alejandro Colomar <alx@kernel.org>
lib/sizeof.h

index 0ee0667a19a4c11d9dbe2d3d446f04746f1e88dc..f16e1a7bf63aed9cc553e02c213ae83cd24bbb01 100644 (file)
 #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