[wish] Flexible array members in unions

David Brown david@westcontrol.com
Fri May 12 12:32:22 GMT 2023


On 12/05/2023 08:16, Richard Biener via Gcc wrote:
> On Thu, May 11, 2023 at 11:14 PM Kees Cook via Gcc <gcc@gcc.gnu.org> wrote:
>>
>> On Thu, May 11, 2023 at 08:53:52PM +0000, Joseph Myers wrote:
>>> On Thu, 11 May 2023, Kees Cook via Gcc wrote:
>>>
>>>> On Thu, May 11, 2023 at 06:29:10PM +0200, Alejandro Colomar wrote:
>>>>> On 5/11/23 18:07, Alejandro Colomar wrote:
>>>>> [...]
>>>>>> Would you allow flexible array members in unions?  Is there any
>>>>>> strong reason to disallow them?
>>>>
>>>> Yes please!! And alone in a struct, too.
>>>>
>>>> AFAICT, there is no mechanical/architectural reason to disallow them
>>>> (especially since they _can_ be constructed with some fancy tricks,
>>>> and they behave as expected.) My understanding is that it's disallowed
>>>> due to an overly strict reading of the very terse language that created
>>>> flexible arrays in C99.
>>>
>>> Standard C has no such thing as a zero-size object or type, which would
>>> lead to problems with a struct or union that only contains a flexible
>>> array member there.
>>
>> Ah-ha, okay. That root cause makes sense now.
> 
> Hmm. but then the workaround
> 
> struct X {
>    int n;
>    union u {
>        char at_least_size_one;
>        int iarr[];
>        short sarr[];
>    };
> };
> 
> doesn't work either.  We could make that a GNU extension without
> adverse effects?
> 
> Richard.
> 

I would like and use an extension like that (for C and C++) - the 
flexible arrays would act as though they were the same size as the 
size-specific part of the union, rounding up in this case to make the 
alignments correct.

I regularly want something like :

	union ProtocolBuffer {
		struct {
			header ...
			data fields ...
		}
		uint8_t raw8[];
		uint32_t raw32[];
	}

The "raw" arrays would be used to move data around, or access it from 
communication drivers.  As C (and C++) is defined, I have to split this 
up so that the "raw" arrays can use "sizeof(ProtocolTelegram) / 4" or 
similar expressions for their size.  If flexible arrays in unions were 
allowed here, it could make my code a little neater and use more 
anonymous unions and structs to reduce unhelpful verbosity.




>> Why are zero-sized objects missing in Standard C? Or, perhaps, the better
>> question is: what's needed to support the idea of a zero-sized object?
>>
>> --
>> Kees Cook
> 




More information about the Gcc mailing list