In C, an array normally isn't allowed to have size 0 (unless I use the one or other compiler-side extension).
OTOH, there are VLAs whose length might turn out to be 0.
Are they allowed?
I am talking about the following code:
void send_stuff()
{
char data[4 * !!flag1 + 2 * !!flag2];
uint8_t cursor = 0;
if (flag1) {
// fill 4 bytes of data into &data[cursor]
cursor += 4;
}
if (flag2) {
// fill 2 bytes of data into &data[cursor]
cursor += 2;
}
}
The result is a data
array with a length of 0, 2, 4 or 6, depending on the combination of the flags.
The question is now: Is this valid code for the case the array turns out to have length 0?
This is not valid, if we go to the draft C99 standard section 6.7.5.2
Array declarators paragraph 5 says (emphasis mine):
if the size is an expression that is not an integer constant expression: if it occurs in a declaration at function prototype scope, it is treated as if it were replaced by *; otherwise, each time it is evaluated it shall have a value greater than zero.[...]
In fact with clang
enabling the sanitizer for undefined behavior using the -fsanitize=undefined
flag can generate a run-time warning for this case see it live:
runtime error: variable length array bound evaluates to non-positive value 0
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With