[cfe-dev] Union with an array of size 1 at end of struct

Nikos Chantziaras realnc at gmail.com
Tue Sep 4 03:00:40 PDT 2012


Normally, Clang emits warnings when it sees array accesses that are out 
of bounds.  Unless the array has a size of 1 and is the last member of a 
struct:

   struct Foo {
       int d;
       struct Foo *array[1];
   };

Then this code won't produce warnings:

   struct Foo *foo = malloc(sizeof(struct Foo) * 3);
   foo->array[1] = NULL;
   foo->array[2] = NULL;

However, this struct:

   struct Bar {
       int d;
       union {
           int n;
           struct Foo *array[1];
       } my_union;
   };

will produce warnings with this code:

   struct Bar *bar = malloc(sizeof(struct Bar) * 3);
   bar->my_union.array[1] = NULL;
   bar->my_union.array[2] = NULL;

Not giving the union a name also doesn't help.

Is this intended?  IMO, if in the first case the compiler stays silent, 
then it should also stay silent in the second one.  Because otherwise it 
means that the code must be rewritten to not use a union, which is a 
compromise; using a union in this case is best way to implement it. 
Passing "-Wno-array-bounds" isn't a good solution either, since it's a 
very helpful warning to have around.

This is C by the way, not C++.




More information about the cfe-dev mailing list