MISRA.ARRAY.VAR_LENGTH.2012MISRA C 2012 Rule 18.8: Variable-length array types shall not be usedC99 [Unspecified 21; Undefined 69, 70] Category: Required Analysis: Decidable, Single Translation Unit Applies to: C99 RationaleVariable-length array types are specified when the size of an array declared in a block or a function prototype is not an integer constant expression. They are typically implemented as a variable size object stored on the stack. Their use can therefore make it impossible to determine statically the amount of memory that must be reserved for a stack. If the size of a variable-length array is negative or zero, the behaviour is undefined. If a variable-length array is used in a context in which it is required to be compatible with another array type, possibly itself variable-length, then the size of the array types shall be identical. Further, all sizes shall evaluate to positive integers. If these requirements are not met, the behaviour is undefined. If a variable-length array type is used in the operand of a sizeof operator, under some circumstances it is unspecified whether the array size expression is evaluated or not. Each instance of a variable-length array type has its size fixed at the start of its lifetime. This gives rise to behaviour that might be confusing, for example: void f ( void ) { uint16_t n = 5; typedef uint16_t Vector[ n ]; /* An array type with 5 elements */ n = 7; Vector a1; /* An array type with 5 elements */ uint16_t a2[ n ]; /* An array type with 7 elements */ } ExampleThere is no use of variable-length arrays that is compliant with this rule. The examples show some of the undefined behaviour that can arise from their use. void f ( int16_t n ) { uint16_t vla[ n ]; /* Non-compliant - Undefined if n <= 0 */ } void g ( void ) { f ( 0 ); /* Undefined */ f ( -1 ); /* Undefined */ f ( 10 ); /* Defined */ } void h ( uint16_t n, uint16_t a[ 10 ][ n ] ) /* Non-compliant */ { uint16_t ( *p )[ 20 ]; /* Undefined unless n == 20: incompatible types otherwise */ p = a; } See alsoRule 13.6 |