Flexible array members are a special type of array where the last element of a structure with more than one named member has an incomplete array type; that is, the size of the array is not specified explicitly within the structure. This "struct hack" was widely used in practice and supported by a variety of compilers. Consequently, a variety of different syntaxes have been used for declaring flexible array members. For C99-compliant implementations, use the syntax guaranteed valid by C99 \[ [ISO/IEC 9899:1999|AA. Bibliography#ISO/IEC 9899-1999]\]. Wiki Markup
Flexible array members are defined in Section 6.7.2.1, paragraph 16 of the C99 standard as follows:
...
Code Block | ||||
---|---|---|---|---|
| ||||
struct flexArrayStruct{ int num; int data[]; }; /* ... */ size_t array_size; size_t i; /* Initialize array_size */ /* Space is allocated for the struct */ struct flexArrayStruct *structP = (struct flexArrayStruct *) malloc(sizeof(struct flexArrayStruct) + sizeof(int) * array_size); if (structP == NULL) { /* Handle malloc failure */ } structP->num = 0; /* Access data[] as if it had been allocated * as data[array_size] */ for (i = 0; i < array_size; i++) { structP->data[i] = 1; } |
This compliant solution allows the structure to be treated as if it had declared the member {{ Wiki Markup data
\[
\]
}} to be {{data
\[array_size
\]
}} in a manner that conforms to the C99 standard.
Risk Assessment
Failing to use the correct syntax can result in undefined behavior, although the incorrect syntax will work on most implementations.
...
ISO/IEC 9899:1999 Section 6.7.2.1, "Structure and union specifiers"
Bibliography
...
\[[McCluskey 2001|AA. Bibliography#McCluskey 01]\] ;login:, July 2001, Volume 26, Number 4
...
02. Declarations and Initialization (DCL) DCL38-C. Use the correct syntax when declaring flexible array members