summaryrefslogtreecommitdiffhomepage
diff options
context:
space:
mode:
authorAlejandro Colomar <alx@nginx.com>2022-11-15 12:24:32 +0100
committerAlejandro Colomar <alx@nginx.com>2022-11-15 13:05:23 +0100
commit269bc8e4e86b6be5cd7acd5ca41b1a86a9032c8c (patch)
treee7a26fc48e7feb52f9ef3a1fd4ade6c245421de8
parent9ea5ed2813c7dc57c8997ef21d779baae19d784c (diff)
downloadunit-269bc8e4e86b6be5cd7acd5ca41b1a86a9032c8c.tar.gz
unit-269bc8e4e86b6be5cd7acd5ca41b1a86a9032c8c.tar.bz2
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 * <https://stackoverflow.com/questions/37538/how-do-i-determine-the-size-of-my-array-in-c/57537491#57537491> */ Signed-off-by: Alejandro Colomar <alx@nginx.com>
-rw-r--r--src/nxt_clang.h4
1 files changed, 4 insertions, 0 deletions
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)