3

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; }; 
3
  • 1
    @Shahbaz: No, int b[] is not the same as int *b. This construct is called a flexible array member. c-faq.com/struct/structhack.html Commented May 10, 2012 at 21:10
  • @jamesdlin, didn't know that! It seems like a terrible idea, though. How could they make it standard? Commented May 10, 2012 at 21:43
  • @Shahbaz It's not a terrible idea, it's just dangerous if people use it wrongly. It was a common hack to have arrays of length 1 as last members of structs for that purpose before it became standard. gcc had long accepted 0-length arrays as flexible array members. Commented May 10, 2012 at 21:47

1 Answer 1

5

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

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.