Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

a struct with a flexible array member in another struct

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;
};
like image 435
ynimous Avatar asked Sep 01 '26 10:09

ynimous


1 Answers

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.)

like image 75
Daniel Fischer Avatar answered Sep 04 '26 08:09

Daniel Fischer



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!