From 269bc8e4e86b6be5cd7acd5ca41b1a86a9032c8c Mon Sep 17 00:00:00 2001 From: Alejandro Colomar Date: Tue, 15 Nov 2022 12:24:32 +0100 Subject: Added nxt_sizeof_array() to safely use sizeof() on arrays. This macro is just sizeof(array), with compiler warnings for when the input is not an array. nxt_nitems() will trigger -Wsizeof-pointer-div when the input is not an array. The multiplication by 0 is to ignore the result of nxt_nitems(), which we only want for the warning. /* * SYNOPSIS * size_t sizeof_array(array); * * ARGUMENTS * array Array to be sized. * * DESCRIPTION * Measure the size of an array --equivalent to sizeof(array)--. * This macro has the benefit that it triggers the warning * '-Wsizeof-pointer-div' when the argument is a pointer instead * of an array, which can cause subtle bugs, sometimes impossible * to detect through tests. * * EXAMPLES * int *p; * int a[1]; * size_t sp, sa; * * sp = sizeof_array(p); // Warning: -Wsizeof-pointer-div * sa = sizeof_array(a); // OK * * SEE ALSO * */ Signed-off-by: Alejandro Colomar --- src/nxt_clang.h | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/src/nxt_clang.h b/src/nxt_clang.h index 94638346..919d9168 100644 --- a/src/nxt_clang.h +++ b/src/nxt_clang.h @@ -251,6 +251,10 @@ nxt_popcount(unsigned int x) (u_char *) ((uintptr_t) (p) & ~((uintptr_t) (a) - 1)) +#define nxt_sizeof_array(a) \ + (sizeof(a) + (0 * nxt_nitems(a))) + + #define nxt_length(s) \ (sizeof(s) - 1) -- cgit