← Back to context

Comment by deletes

12 years ago

Thank you for that.

That surprised me. I thought( and read somewhere ) that the flexible array member comes right after the entire struct, which includes possible padding.

OP got away with it since he always allocates the size of the entire struct, which is 8, plus the string size. And since char doesn't have any alignment requirements it doesn't matter, because he always gets back to correct offset. So data member is basically not used, and if you check the code you will see that it actually in never used!

The standard actually specifies (or specified?) that the flexible array member must come after all the members, including the padding. But, from my reading, that wasn't their intent, and is certainly not how compilers implement it. The link in my original post is an acknowledgement from the committee about this and that the standard needs to be updated.

I think the main reason the OP got away with it is because in his structure, "sizeof(struct sdshdr)" is equal to the offset of "buf" in the struct. This is not necessarily true.

In particular, see the latest C standard draft (http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1570.pdf), section 6.7.2.1 (Structure and union specifiers), paragraph 18 and 20-21. An example in the standard uses this code:

    struct s { int n; double d[]; };

and says that "but it is possible that"

    sizeof (struct s) >= offsetof(struct s, d) + sizeof (double)

  • Yeah I was wrong on that, he must have sizes 8 both. My compiler gives 5 and 8.

    Coincidentally I just read that specific paragraph earlier today for totally different reasons. :)

    Will have to recheck some code.