CERT.STRUCT.FLEXIBLE_ARRAY_MEMBER

Use the correct syntax when declaring a flexible array member.

This checker identifies instances where a flexible array-like member is declared as a one-element array.

Vulnerability and risk

Failing to use the correct syntax when declaring a flexible array member can result in undefined behavior, although the incorrect syntax will work on most implementations.

Mitigation and prevention

Declare the flexible array member as dynamically sized.

Example

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;
    }
}

This noncompliant code example attempts to allocate a flexible array-like member with a one-element array as the final member. When the structure is instantiated, the size computed for malloc() is modified to account for the actual size of the dynamic array.