Skip to content
Tutorials Center
My learning

Topics

Lesson 64 of 135 ยท Structures and Unions

Flexible Array Members

Use a C99 flexible array member to store a header and a variable-length array in one malloc block, with correct sizing, growing, copying and the rules to avoid.

Sometimes a struct describes a header followed by a variable amount of data: a network packet with a length field and a payload, a string with a stored length, a list of values with a count. You don't know the amount of data until run time, so a fixed array member (char data[256]) either wastes space or caps the size.

One common answer is a pointer member (char *data) pointing to a second allocation. C99 offers a tighter alternative: the flexible array member, an array with no size declared as the last member of a struct. The header and the data live together in a single block of memory. This lesson shows how to declare, allocate, grow and copy such structs, and the restrictions that come with them. It builds on Structures and Dynamic Memory.

Declaring one

A flexible array member is declared with empty brackets, and it must be the last member of a struct that has at least one other named member:

C
struct text {
    size_t length;     /* at least one other member is required */
    char chars[];      /* flexible array member: must come last */
};

chars takes no space in the struct by itself. sizeof(struct text) covers only length (plus any padding), so by itself the struct holds zero characters. You get the extra room by allocating more memory than sizeof says: header size plus the bytes for the elements you want.

flowchart LR
    subgraph "one malloc block"
        A["length<br/>(size_t, 8 bytes)"] --> B["chars[0]"] --> C["chars[1]"] --> D["..."] --> E["chars[n-1]"]
    end
    P["struct text *t"] --> A

The header and the elements share one allocation; the flexible member begins right after the fixed members.

Allocating and using it

For n elements, allocate sizeof *t + n * sizeof t->chars[0]. (The old GNU char data[0] and C89 char data[1] tricks that you may see in legacy code do the same job, but they are non-standard or undefined behavior; use the empty brackets.)

C A length-prefixed string in one allocation

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Just one malloc and one free. With a pointer member (char *chars) you'd need two allocations, two error checks, and two free calls in the right order.

Compare the two layouts side by side:

Flexible array member Pointer member
Allocations 1 2
Cache locality Header and data are adjacent Data may be far from the header
sizeof(struct) Header only Header plus one pointer
Can resize data freely Only by reallocating the whole struct (address may change) Yes, reallocate just the data
Can copy the struct by assignment Copies the header only Copies the pointer (shallow copy)

sizeof versus offsetof

There is a subtle point when sizing the allocation. sizeof(struct) includes trailing padding (see Padding and Alignment), but the flexible member begins at offsetof(struct, member), which can be smaller than sizeof. Using sizeof *t + n * element_size is always large enough; using offsetof(...) + n * element_size is the tightest valid size. Both are correct, and the difference is a few bytes.

C sizeof is not always where the array starts

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

For packet, the char payload could start at byte 9, but the struct is padded to a multiple of 8 for the double, giving a sizeof of 16. For samples, the double array must be 8-byte aligned, so it starts at byte 8, which is the same as sizeof. On the 64-bit Linux compiler used by our editor, you will see 16 and 9 for the first and 8 and 8 for the second.

An array of numbers that grows

Because the flexible member is just memory after the header, you can realloc the whole block to make room for more elements. Remember that realloc can move the block, so you must use the pointer it returns, and never keep old pointers into the array.

C A growable list stored in a single block

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

The capacity doubles from 2 to 4 to 8 as the list fills, and the program prints each step. This is the same doubling strategy as the one in Dynamic Arrays, but the header and data stay in one block.

Rules and pitfalls

The restrictions all follow from the member having no size of its own:

  • Last member only, and the struct needs at least one named member before it.
  • sizeof ignores it. Never rely on sizeof(struct) to tell you how much data a block holds; store a count or length field yourself.
  • Assignment copies only the header. *b = *a for such structs copies the fixed members and ignores the array. To duplicate, allocate a new block and memcpy the right number of bytes:
C
struct list *list_clone(const struct list *src)
{
    size_t bytes = sizeof *src + src->count * sizeof src->items[0];
    struct list *copy = malloc(bytes);
    if (copy != NULL) {
        memcpy(copy, src, bytes);
        copy->capacity = copy->count;
    }
    return copy;
}
  • Passing and returning by value is a mistake for the same reason: only the header travels. Always pass a pointer.
  • No arrays and no nesting. You can't make an array of these structs (the elements would have different sizes), and the standard says a struct with a flexible array member should not be a member of another struct or an element of an array.
  • No static initialization of the elements. static struct list l = {0, 0, {1, 2, 3}}; is not standard C (GCC allows it as an extension). Allocate with malloc and fill the elements by hand, or use a different design.
  • Don't take the array's size with sizeof t->items: that is a constraint violation because the type is incomplete.
  • Keep the count correct. The compiler can't see how many elements were allocated, so writing past the allocated amount is an ordinary buffer overflow (see Memory Errors). Tools like AddressSanitizer catch it.

Tip: Recent GCC and Clang versions let you annotate the count field, as in size_t count; int items[] __attribute__((counted_by(count)));. With -fsanitize=bounds or _FORTIFY_SOURCE=3, the compiler can then check indexes against the real length. It is a compiler extension (not standard C23), but worth using where available.

When to use a flexible array member

It fits well when:

  • The size is fixed when the object is created (a parsed message, a string with a stored length, an AST node with N children).
  • You want one allocation and good locality.
  • The object travels around only through pointers.

Prefer a pointer member when the data needs to grow or shrink independently of the header, when the struct needs to be copied by value, or when you need arrays of such structs.

If you meet char data[1] or char data[0] in older code, that's the pre-C99 "struct hack" doing the job flexible arrays now do properly. Update it to char data[] when you can. The same feature exists in C++ only as a compiler extension, and the C reference has a dedicated page on flexible array members.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Where must a flexible array member appear in a struct?

    The array has no size, so it must be last (it extends into whatever extra memory follows the struct). A lone flexible array and no other member is not allowed.
  2. 2. Given struct s { int n; char data[]; };, what is the correct way to allocate room for 10 chars?

    The header size is added to the bytes for the elements. Allocating only sizeof(struct s) leaves no room for any data.
  3. 3. What does the assignment *b = *a do when both are struct list with a flexible array member?

    sizeof ignores the flexible member, so the copy covers only the header. To duplicate the whole object, allocate a block of the right size and use memcpy.
  4. 4. Why must you use the pointer returned by realloc when growing a struct with a flexible array member?

    realloc may extend the block in place or move it. Only the returned pointer is guaranteed to be valid.
  5. 5. What does sizeof(struct s) tell you for a struct with a flexible array member?

    The flexible member contributes nothing to sizeof, so you must track the element count yourself.

Summary

  • A flexible array member (C99) is an array with empty brackets as the last member of a struct that has at least one other member.
  • It contributes nothing to sizeof; allocate sizeof *p + n * sizeof element bytes to give it n elements.
  • Header and data share one allocation: one malloc, one free, and better cache locality than a pointer member.
  • Use offsetof to see where the array starts, and store the element count yourself.
  • Grow with realloc and use the returned pointer; copy with memcpy of the full size, because assignment copies only the header.
  • You can't make arrays of such structs, pass them by value or initialize the elements statically; pass pointers instead.

Next: The Preprocessor