defs: add check for argument being array to ARRAY_SIZE macro

* gcc_compat.h [GNUC_PREREQ(3, 0)] (BUILD_BUG_ON_ZERO): New macro.
(SAME_TYPE, MUST_BE_ARRAY): Likewise.
* defs.h (ARRAY_SIZE): Add MUST_BE_ARRAY for build-time type check.
This commit is contained in:
Eugene Syromyatnikov 2016-10-29 05:24:08 +03:00
parent a1a42e1f0d
commit 48252db2a2
2 changed files with 11 additions and 1 deletions

2
defs.h
View File

@ -73,7 +73,7 @@ extern char *stpcpy(char *dst, const char *src);
(offsetof(type, member) + sizeof(((type *)NULL)->member))
#endif
#define ARRAY_SIZE(a) (sizeof(a) / sizeof((a)[0]))
#define ARRAY_SIZE(a) (sizeof(a) / sizeof((a)[0]) + MUST_BE_ARRAY(a))
/* macros */
#ifndef MAX

View File

@ -52,6 +52,16 @@
# define ATTRIBUTE_PACKED /* empty */
#endif
#if GNUC_PREREQ(3, 0)
# define SAME_TYPE(x, y) __builtin_types_compatible_p(typeof(x), typeof(y))
# define BUILD_BUG_ON_ZERO(expr) (sizeof(int[-1 + 2 * !!(expr)]) * 0)
/* &(a)[0] is a pointer and not an array, shouldn't be treated as the same */
# define MUST_BE_ARRAY(a) BUILD_BUG_ON_ZERO(!SAME_TYPE((a), &(a)[0]))
#else
# define SAME_TYPE(x, y) 0
# define MUST_BE_ARRAY(a) 0
#endif
#if GNUC_PREREQ(3, 0)
# define ATTRIBUTE_MALLOC __attribute__((__malloc__))
#else