Re: Expanding the use of FLEXIBLE_ARRAY_MEMBER for declarations like foo[1]

From: Andres Freund <andres(at)2ndquadrant(dot)com>
To: Tom Lane <tgl(at)sss(dot)pgh(dot)pa(dot)us>
Cc: Michael Paquier <michael(dot)paquier(at)gmail(dot)com>, PostgreSQL mailing lists <pgsql-hackers(at)postgresql(dot)org>
Subject: Re: Expanding the use of FLEXIBLE_ARRAY_MEMBER for declarations like foo[1]
Date: 2015-02-19 09:49:31
Message-ID: 20150219094931.GE16383@alap3.anarazel.de
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-hackers

On 2015-02-18 17:29:27 -0500, Tom Lane wrote:
> Michael Paquier <michael(dot)paquier(at)gmail(dot)com> writes:
> > On Wed, Feb 18, 2015 at 10:09 PM, Andres Freund <andres(at)2ndquadrant(dot)com> wrote:
> >> The compiler will complain if you use a FLEXIBLE_ARRAY_MEMBER in the
> >> middle of a struct but not when when you embed a struct that uses it
> >> into the middle another struct. At least gcc doesn't and I think it'd be
> >> utterly broken if another compiler did that. If there's a compiler that
> >> does so, we need to make it define FLEXIBLE_ARRAY_MEMBER to 1.
>
> > clang does complain on my OSX laptop regarding that ;)
>
> I'm a bit astonished that gcc doesn't consider this an error. Sure seems
> like it should.

Why? The flexible arrary stuff tells the compiler that it doesn't have
to worry about space for the array - it seems alright that it actually
doesn't. There's pretty much no way you can do that sensibly if the
variable length array itself is somewhere in the middle of a struct -
but if you embed the whole struct somewhere you have to take care
yourself. And e.g. the varlena cases Michael has shown do just that?

> (Has anyone tried it on recent gcc?)

Yes.

> Moreover, if we have any code that is assuming such cases are okay, it
> probably needs a second look. Isn't this situation effectively assuming
> that a variable-length array is fixed-length?

Not really. If you have
struct varlena hdr;
char data[TOAST_MAX_CHUNK_SIZE]; /* make struct big enough */
the variable length part is preallocated in the data?

You're right that many of these structs could just be replaced with a
union though.

Greetings,

Andres Freund

--
Andres Freund http://www.2ndQuadrant.com/
PostgreSQL Development, 24x7 Support, Training & Services

In response to

Browse pgsql-hackers by date

  From Date Subject
Next Message Andres Freund 2015-02-19 09:54:53 Re: Expanding the use of FLEXIBLE_ARRAY_MEMBER for declarations like foo[1]
Previous Message Dean Rasheed 2015-02-19 08:07:53 Re: Odd behavior of updatable security barrier views on foreign tables