If we have structure with flexible member array like :-
struct test{
int n;
int b[];
};
Then even before malloc is done, If we try to print like :-
struct test t;
printf("%lu",sizeof(t.b[0]);
Does this fall under Undefined behaviour?
C99 says this about flexible member arrays :-
"If this array would have no elements, it behaves as if it had one element but the behaviour is undefined if any attempt is made to access that element or to generate a pointer one past it."
So accessing b[0]
is undefined behaviour but will it apply to sizeof operator too given it is compile-time operator and t.b[0]
is never accessed here at runtime?
When I tried this in gcc compiler, I have output as 4 bytes but if it falls under undefined behaviour, then we cannot take this output for granted until and unless gcc has given some extension which I am not sure in this case.
CodePudding user response:
Since the argument to sizeof
is not evaluated (unless, VLA), you're safe here.
In your case, t.b[0]
is a complete type, int
- to be specific. hence this is well defined. Matter of fact, you can also use sizeof(t.b[100])
, since it's not evaluated, the index value won't matter.
CodePudding user response:
sizeof
doesn't evaluate its operand unless you pass a VLA. You can't pass it a flexible array member either because that's an incomplete type.
However, sizeof(b[0])
is fine and well-defined, as it is an individual item of type int
. The operand is not evaluated.