a struct with a flexible array member in another struct

c, flexible-array-member

Solution

It's not okay. Section 6.7.2.1 (in n1570), point 3 says

3 A structure or union shall not contain a member with incomplete or function type (hence, a structure shall not contain an instance of itself, but may contain a pointer to an instance of itself), except that the last member of a structure with more than one named member may have incomplete array type; such a structure (and any union containing, possibly recursively, a member that is such a structure) shall not be a member of a structure or an element of an array.

So a `struct` with a flexible array member may not be part of another struct.

(It may well work as the last member of a struct, though, if the compiler accepts it.)

Problem

Is something like the code below valid? ``` struct foo { int a; int b[]; }; struct bar { int c; struct foo d; }; struct bar *x = malloc(sizeof(struct bar) + sizeof(int [128])); ``` It seems ok to me, but I am a bit skeptical because compiler does not complain if I do: ``` struct bar { struct foo d; int c; }; ```

Original source