2

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.

2
  • 3
    note: use %zu to print the result of sizeof operator, it has type size_t Commented Nov 3, 2022 at 7:59
  • 1
    No, that's perfectly fine. The same is true for the common malloc pattern int *a = malloc(5 * sizeof *a);. sizeof only evalutes the type, not the value. Commented Nov 3, 2022 at 8:00

2 Answers 2

5

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.

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

1 Comment

Thanks everyone, this clears my confusion.
3

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.