This is the mail archive of the
gcc-help@gcc.gnu.org
mailing list for the GCC project.
Re: Safer determination of static array size
- From: Marcin Sobieszczanski <marciso dot gcc at gmail dot com>
- To: Florian Weimer <fweimer at redhat dot com>
- Cc: gcc-help at gcc dot gnu dot org
- Date: Fri, 9 Aug 2013 14:26:59 +0100
- Subject: Re: Safer determination of static array size
- References: <5204E23B dot 4030303 at redhat dot com> <CANSnWPhz1kWmYpBM2YzLu6pfe0=DS4yxrdgwQTBTB_WJL-qCTA at mail dot gmail dot com> <5204E5A8 dot 4060003 at redhat dot com>
Linux kernel does it this way:
/* Force a compilation error if condition is true, but also produce a
result (of value 0 and type size_t), so the expression can be used
e.g. in a structure initializer (or where-ever else comma expressions
aren't permitted). */
#define BUILD_BUG_ON_ZERO(e) (sizeof(char[1 - 2 * !!(e)]) - 1)
/* &a[0] degrades to a pointer: a different type from an array */
#define __must_be_array(a) \
BUILD_BUG_ON_ZERO(__builtin_types_compatible_p(typeof(a), typeof(&a[0])))
#define ARRAY_SIZE(arr) (sizeof(arr) / sizeof((arr)[0]) + __must_be_array(arr))
On Fri, Aug 9, 2013 at 1:50 PM, Florian Weimer <fweimer@redhat.com> wrote:
> On 08/09/2013 02:49 PM, Marcin Sobieszczanski wrote:
>>
>> What about a template function:
>>
>> template<typename T, size_t SZ> size_t ARRAY_SIZE( T (&a) [SZ] ) {
>> return SZ; }
>
>
> Yes, that's a good approach for C++ code, but a lot of code I'm dealing with
> only compiles as C.
>
>
> --
> Florian Weimer / Red Hat Product Security Team