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

Nikos Chantziaras realnc at gmail.com
Tue Sep 4 12:46:08 PDT 2012


On 04/09/12 19:44, John McCall wrote:
> On Sep 4, 2012, at 3:00 AM, Nikos Chantziaras wrote:
>> 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.
>
> I agree that accesses to [0]- or [1]-bounded arrays in embedded unions or at the ends of embedded structs should also be white-listed by this warning.  Please file a bug.

I just filed one:

http://llvm.org/bugs/show_bug.cgi?id=13766




More information about the cfe-dev mailing list