Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Variable Length Array with length 0?

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?

like image 791
glglgl Avatar asked Dec 19 '22 14:12

glglgl


1 Answers

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

like image 180
Shafik Yaghmour Avatar answered Dec 27 '22 15:12

Shafik Yaghmour