Flexible Array Members

suggest change

A structure with at least one named member may end with an array of unspecified size. This final member is a flexible array member:

#include <stddef.h>
#include <stdint.h>

struct packet {
    size_t length;
    unsigned char data[];
};

The member has an incomplete array type, so sizeof packet.data is invalid. sizeof(struct packet) excludes the array elements, although it may include additional trailing padding. Use offsetof(struct packet, data) when calculating the exact prefix before the array.

Allocation

Allocate the structure and its elements as one object, checking arithmetic before allocation:

#include <stddef.h>
#include <stdint.h>
#include <stdlib.h>

struct packet *packet_create(size_t length)
{
    size_t prefix = offsetof(struct packet, data);
    if (length > SIZE_MAX - prefix) {
        return NULL;
    }

    struct packet *packet = malloc(prefix + length);
    if (packet != NULL) {
        packet->length = length;
    }
    return packet;
}

If packet_create(n) succeeds, elements packet->data[0] through packet->data[n - 1] can be used. Release the complete object with one call to free(packet).

The flexible array member cannot be initialized directly:

struct packet empty = {.length = 0}; /* Valid; no data elements. */

Do not place a structure containing a flexible array member inside an array or as a member of another structure. Its special layout is intended for a separately allocated trailing payload, not a variable-size stride between array elements.

Portability

Flexible array members were introduced in C99. Older “struct hack” declarations such as unsigned char data[1] have different sizeof behavior and do not gain all the language rules of a true flexible array member. Prefer the standard form when the target supports it.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents