...
- The incomplete array type must be the last element within the structure.
- There cannot be an array of structures that contain flexible array members.
- Structures that contain a flexible array member cannot be used as a member in the middle of another structure.
- The
sizeof
operator cannot be applied to a flexible array.
Noncompliant Code Example (Declaration Example 2)
When using structures with a flexible array member you should never directly declare an instance of the structure. The following code snippet illustrates this.
Code Block |
---|
|
struct flexArrayStruct{
int num;
int data[];
};
/* ... */
struct flexArrayStruct flexStruct;
size_t array_size;
size_t i;
/* Initialize array_size */
/* Initialize structure */
flexStruct.num = 0;
for (i = 0; i < array_size; i++) {
flexStruct.data[i] = 0;
}
|
Wiki Markup |
---|
The problem with this code is that the flexArrayStruct does not actually reserve space for the integer array data - it can't as the size hasn't been specified. Thus, while initializing the num member to zero is ok, attempting to write even one value into data (i.e. data\[0\]) will likely overwrite memory not owned by the structure. |
Compliant Code Example (Declaration Example 2)
The solution is to always declare pointers to structures containing a flexible array member and dynamically allocate memory for them. The following code snippet illustrates this.
Code Block |
---|
|
struct flexArrayStruct{
int num;
int data[];
};
/* ... */
struct flexArrayStruct *flexStruct;
size_t array_size;
size_t i;
/* Initialize array_size */
/* Dynamically allocate memory for the structure */
flexStruct = (struct flexArrayStruct *)
malloc(sizeof(struct flexArrayStruct) + sizeof(int) * array_size);
if (flexStruct == NULL) {
/* Handle malloc failure */
}
/* Initialize structure */
flexStruct->num = 0;
for (i = 0; i < array_size; i++) {
flexStruct->data[i] = 0;
}
|
Wiki Markup |
---|
In this code snippet the resolves the issue by declaring a pointer to flexArrayStruct and then dynamically allocating memory for the pointer to point to. In this case it is ok to access the elements of the data\[\] member as described in Section 6.7.2.1, paragraph 16. |
Noncompliant Code Example (Reference)
In this noncompliant code, the flexible array structure is passed directly to a function which tries to print the array elements. This fails because passing the struct directly to the function actually makes a copy of the struct. When the struct is copied, the size of the flexible array member is not considered, consequently the array is truncated, and the function only has garbage in the array to print.
...