Skip to content

Commit 62947de

Browse files
committed
util: ensure that array is passed to ARRAY_SIZE
Possible if C11 or later is supported (needed for `_Static_assert`) and gcc/clang is used (needed for `__typeof__`).
1 parent 4eece18 commit 62947de

1 file changed

Lines changed: 9 additions & 1 deletion

File tree

src/util.h

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -181,7 +181,15 @@ static SECP256K1_INLINE void *checked_malloc(const secp256k1_callback* cb, size_
181181

182182
#define ROUND_TO_ALIGN(size) (CEIL_DIV(size, ALIGNMENT) * ALIGNMENT)
183183

184-
#define ARRAY_SIZE(arr) (sizeof(arr) / sizeof((arr)[0]))
184+
#if defined(__GNUC__) && (__STDC_VERSION__ >= 201112L)
185+
# define __BUILD_BUG_ON_ZERO_MSG(e, msg) ((int)sizeof(struct {int dummy; _Static_assert(!(e), msg);}))
186+
# define __same_type(a, b) __builtin_types_compatible_p(__typeof__(a), __typeof__(b))
187+
# define __is_array(a) (!__same_type((a), &(a)[0]))
188+
# define __must_be_array(a) __BUILD_BUG_ON_ZERO_MSG(!__is_array(a), "must be array")
189+
# define ARRAY_SIZE(arr) (sizeof(arr) / sizeof((arr)[0]) + __must_be_array(arr))
190+
#else
191+
# define ARRAY_SIZE(arr) (sizeof(arr) / sizeof((arr)[0]))
192+
#endif
185193

186194
/* Macro for restrict, when available and not in a VERIFY build. */
187195
#if defined(SECP256K1_BUILD) && defined(VERIFY)

0 commit comments

Comments
 (0)