2

I have the following code:

#include <cstdint>

struct parent
{
   uint64_t   id;    
   char       data[];
};

struct child : public parent
{
   uint32_t tmp;
   char text[];
};

int main() {
    child d;
    d.id = 1;
}

When compiled with GCC 7.2.1, it gave me errors:

flex.cpp:6:20: error: flexible array member ‘parent::data’ not at end of ‘struct child’
    char       data[];
                    ^
flex.cpp:11:13: note: next member ‘uint32_t child::tmp’ declared here
    uint32_t tmp;
             ^~~
flex.cpp:9:8: note: in the definition of ‘struct child’
 struct child : public parent
        ^~~~~

When compiled with GCC 4.8.5, it's fine with no warning nor error.

A bug in GCC 4.8.5?

Thanks in advance!

Lundin
  • 195,001
  • 40
  • 254
  • 396
Hei
  • 1,844
  • 3
  • 21
  • 35

1 Answers1

1

Yes, this looks like a bug in GCC 4.8. The memory used by the subclass comes after that of the superclass. The flexible array member is syntactically at the end of the superclass, but not for the memory layout of the whole object. This is similar to the C case involving composition:

struct parent
{
   uint64_t   id;    
   char       data[];
};

struct child
{
   struct parent parent;
   uint32_t tmp;
   char text[];
};

This is not valid C, either, although GCC 7 and earlier only warn with -pedantic (which is a bit reckless in my opinion).

Note that flexible array members are a GNU extension and not part of the C++ standard.

Florian Weimer
  • 32,022
  • 3
  • 48
  • 92
  • Thanks for your input. I heard flexible array is part of C99 standard. So I am curious whether C99 standard guarantees the memory layout that the superclass' member(s) will precede the child class' (assuming text[] is removed from the child class to give a valid declaration). – Hei Nov 11 '17 at 13:14
  • C does not have classes, so I don't understand your question. I believe the fragment I posted is invalid under C, but GCC does not diagnose that by default. – Florian Weimer Nov 11 '17 at 13:21
  • Hmm...the superclass I mentioned refers to struct parent, and child class struct child. But C doesn't support inheritance. So I guess my question is still invalid. – Hei Nov 12 '17 at 00:46