An array of variable length with a length of 0?

In C, an array is usually not allowed to be of size 0 (unless I use one or the other extension on the compiler side).

OTOH, there are VLAs whose length may 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 flags.

The question is, is this valid code for the case when the array is 0 in length?

+3
source share
1 answer

This is not true if we go on to draft the draft C99 6.7.5.2 The statement in paragraph 5 says (focus):

if the size is an expression that is not an integer constant expression: if it occurs in the declaration in the scope of the function prototype, it is processed as if it were replaced by *; otherwise, each time it is evaluated , it must have a value greater than zero . [...]

In fact, with clang allowing a sanitizer for undefined behavior using the -fsanitize=undefined flag, -fsanitize=undefined can generate a run-time warning for this case to watch live :

Runtime error: variable array length associated with non-positive value 0

+9
source

Source: https://habr.com/ru/post/970732/


All Articles