CERT-DCL38-C
In this section:
Synopsis
Use the correct syntax when declaring a flexible array member.
Enabled by default
Yes
Severity/Certainty
Low/Low

Full description
A variety of different syntaxes have been used for declaring flexible array members. For conforming C implementations, use the syntax guaranteed to be valid by the C Standard.
Coding standards
- CERT DCL38-C
Use the correct syntax when declaring flexible array members
Code examples
The following code example fails the check and will give a warning:
#include <stdlib.h>
struct flexArrayStruct {
int num;
int data[1];
};
void func(size_t array_size) {
/* Space is allocated for the struct */
struct flexArrayStruct *structP
= (struct flexArrayStruct *)
malloc(sizeof(struct flexArrayStruct)
+ sizeof(int) * (array_size - 1));
if (structP == NULL) {
/* Handle malloc failure */
}
structP->num = array_size;
/*
* Access data[] as if it had been allocated
* as data[array_size].
*/
for (size_t i = 0; i < array_size; ++i) {
structP->data[i] = 1;
}
}
The following code example passes the check and will not give a warning about this issue:
#include <stdlib.h>
struct flexArrayStruct {
int num;
int data[];
};
void func(size_t 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 = array_size;
/*
* Access data[] as if it had been allocated
* as data[array_size].
*/
for (size_t i = 0; i < array_size; ++i) {
structP->data[i] = 1;
}
}