This code used to work prior to gcc-7.1 (it worked on 4.x, and — I just tested — 6.3 works too, with a warning though): struct DataPacket { /* … */ unsigned szdata; char data[]; }; struct AckPacket { DataPacket header; int a,b,c; }; int main() { return 0; } However gcc-7.1 bails out with: λ g++ test.cpp -o a test.cpp:4:12: error: flexible array member ‘DataPacket::data’ not at end of ‘struct AckPacket’ char data[]; ^ test.cpp:9:6: note: next member ‘int AckPacket::a’ declared here int a,b,c; /* no data below */ ^ test.cpp:7:8: note: in the definition of ‘struct AckPacket’ struct AckPacket { Imo the code is fine. Though I'm open to suggestions into a better design too.
The code is valid in C, so presumably should be valid with G++ too. GCC 6 gives a warning with -pedantic, but prints the accompanying notes even without -pedantic! $ g++ foo.c -pedantic foo.c:4:27: warning: flexible array member ‘DataPacket::data’ not at end of ‘struct AckPacket’ [-Wpedantic] char data[]; ^ foo.c:9:21: note: next member ‘int AckPacket::a’ declared here int a,b,c; ^ foo.c:7:16: note: in the definition of ‘struct AckPacket’ struct AckPacket { ^~~~~~~~~ $ g++ foo.c foo.c:9:21: note: next member ‘int AckPacket::a’ declared here int a,b,c; ^ foo.c:7:16: note: in the definition of ‘struct AckPacket’ struct AckPacket { ^~~~~~~~~
The orhpaned notes started with r231665 and the pedwarn became an error with r241143
The C constraint is that a flexible array member must be the last member of a struct. In addition, such a struct may not not be used to define a member in another struct (not even as the last member). These constraints prevent aliasing between such a member and those that follow. In C, mode GCC accepts the test case from comment #0 but with -Wpedantic issues a warning: t.c:8:14: warning: invalid use of structure with flexible array member [-Wpedantic] G++ 7 is intentionally more strict here and rejects the code (the checking was tightened up in r241143). The stray notes in GCC 6 (without -Wpedantic) are a 6.3 regression. To avoid the error (and accept the risks of the array aliasing with members stored at the same address) define data as a zero-length array (https://gcc.gnu.org/onlinedocs/gcc/Zero-Length.html).
(In reply to Martin Sebor from comment #3) > In C, mode GCC accepts the test case from comment #0 but with -Wpedantic > issues a warning: > > t.c:8:14: warning: invalid use of structure with flexible array member > [-Wpedantic] Ah, I missed that when checking with the C front end, thanks.
GCC 6.4 is being released, adjusting target milestone.
Not a bug.