Programming · free software · the open webSubscribe via RSS

A C flexible array member is an allocation contract

A flexible array member puts a variable-length tail next to a fixed C structure, but the type does not allocate that tail or remember its length. Correct use depends on layout-aware sizing, overflow checks and an explicit count contract.

The type describes a tail, not its storage

A C structure with a flexible array member joins a fixed header to a variable-length sequence in one allocation. For example, struct packet { size_t count; unsigned char bytes[]; }; puts a count and its payload under one owning pointer. The array is incomplete in the declaration and must be the final member of a suitable structure. This is useful for compact objects whose header and payload share a lifetime, such as a parsed record or an in-memory message. [1]

The declaration does not make each struct packet large enough for an arbitrary payload. The pointer still refers to one allocated object, and the caller must choose a size that includes the fixed structure plus the desired tail. The flexible array does not remember its allocated length: count is ordinary application data. If it disagrees with the allocation, indexing can run beyond the object. Think of the declaration as a layout recipe plus an external size invariant, not a dynamically resizing member.

Why sizeof is the fixed-size part

For a structure with a flexible array member, sizeof *p gives the size of the structure as if the array member were omitted, though the implementation may include extra trailing padding. C11’s committee draft gives the conventional allocation as the size of the structure plus the size of an array with the requested element count. Its member-access rule then treats the tail as the longest array that fits inside the actual object. [1]

That makes sizeof *p + count * sizeof p->bytes[0] a sensible formula: the first term preserves implementation padding, and the second accounts for requested elements. The member offset and structure size are related but are not promised to be identical. A hard-coded header length turns implementation layout into an undocumented file format. WG14’s padding correction records the reason for this flexibility. [2]

Check the arithmetic before asking malloc

The formula is not safe until its arithmetic is safe. size_t arithmetic wraps modulo its range. If count * element_size wraps to a small number, malloc can succeed with an undersized object while later code still trusts the original count. Checking whether the returned pointer is null only handles allocation failure; it cannot detect a size that was already computed incorrectly. CERT’s MEM35-C rule calls out overflow, truncation and inadequate range checks as ways to request too little storage. [3]

For a positive element size, bound the count before multiplication and addition. In this structure the relevant condition is count <= (SIZE_MAX - sizeof *p) / sizeof p->bytes[0]. If it fails, reject the input or report a size error; otherwise compute sizeof *p + count * sizeof p->bytes[0] and allocate that many bytes. The subtraction is safe because sizeof *p is itself representable as size_t, and division expresses the maximum count that leaves room for the fixed part. Check the count’s conversion into size_t too if it came from a wider wire integer. [3]

An attacker-controlled count may be arithmetically valid yet request unreasonable memory. Apply a separate protocol or product limit: the overflow check protects the size calculation, not whether the request is affordable or allowed.

Keep the count attached to the same allocation

The header count is part of the contract because a pointer to the structure does not carry its allocation length. Initialize the count from the validated value used in the size calculation, and pass the object as one unit where possible. If code accepts a pointer and count as separate arguments, document which one is authoritative and verify that their relationship is maintained. A count copied from an untrusted header should not silently become the bounds for an allocation made with a different value.

A second subtlety is structure assignment. *destination = *source assigns the declared structure members, but it does not copy the flexible array’s tail. The C11 example explicitly calls out that only the fixed member is copied. A variable-sized object therefore needs a deliberate copy operation sized from the allocation contract: allocate the destination for its tail, copy the fixed fields, then copy exactly the validated number of tail bytes. [1]

Zero is also a policy case, not a reason to index the member. An object may carry a header and no payload, but code must not infer a valid first element merely because some implementations place padding after the fixed fields. Keep zero-count handling explicit and avoid dereferencing bytes[0] when the logical count is zero.

Use the pattern where co-location buys something

A flexible array member is most useful when the header and elements share ownership, are created together and are usually consumed together. It can reduce separate allocations and make the object’s payload lifetime easy to follow. It is less attractive when the tail needs independent growth, when multiple parts of a program retain interior pointers across reallocations, or when the length has no trustworthy owner. In those cases, a separately managed buffer or a container abstraction may make the lifetime and capacity rules easier to state.

A review can trace the validated count, checked allocation size, stored count and loop bounds back to one input. They should agree by construction. The flexible member supplies a compact representation; correctness depends on keeping that relationship explicit.

References

  1. WG14 N1570: C11 committee draft, flexible array members
  2. WG14: C issue 0282, flexible array members and structure padding
  3. SEI CERT C: MEM35-C, allocate sufficient memory for an object

Suggest a correction · All posts