YOUR C LEARNING COMPANION

Find your next idea.

Learning path
Designing dataChapter 36 of 73

Flexible array members

Build a checked header-plus-payload model with explicit allocation size, logical length, copying, and ownership.

6 min readCore conceptsC17 baseline
Offline reading
In this chapter8 sections
0% through this chapter

A record may need a variable amount of data after its fixed members. A flexible array member supports that arrangement, but the allocation must make room for the data. The stored length and the actual available capacity must agree.

1. A flexible member describes a tail, not a pointer

A flexible array member is an incomplete array as the last member of a structure with at least one other named member. Its elements occupy storage in the same allocated object after the appropriate member offset. This differs from a pointer member, which stores an address and can refer to a separate allocation. The empty brackets are not a standard zero-length array declaration.

One allocation
fixed information
length = 3
flexible payload
data[0], data[1], data[2]
Logical regions, not exact byte boundaries. Padding and the member offset are accounted for by the checked allocation; length remains the access bound.

2. Allocate and initialize the intended payload

This byte-buffer example uses unsigned char, so each payload element is one C byte. Include <stdlib.h> for allocation and <stdint.h> for SIZE_MAX. Assertions use <assert.h>. The helper rejects an overflowing total, checks allocation failure, records the logical length, and initializes the payload before returning ownership.

Complete C17 program
#include <assert.h>
#include <stdint.h>
#include <stdlib.h>

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

static struct Buffer *make_buffer(size_t length)
{
    if (length > SIZE_MAX - sizeof(struct Buffer)) return NULL;
    struct Buffer *buffer = malloc(sizeof *buffer + length);
    if (buffer == NULL) return NULL;
    buffer->length = length;
    for (size_t i = 0; i < length; ++i) buffer->data[i] = 0;
    return buffer;
}

int main(void)
{
    struct Buffer *buffer = make_buffer(3);
    if (buffer == NULL) return EXIT_FAILURE;
    buffer->data[0] = 4;
    buffer->data[2] = 6;
    assert(buffer->length == 3);
    assert(buffer->data[1] == 0);
    assert(buffer->data[2] == 6);
    free(buffer);
    return 0;
}

The extra allocation is deliberate. Merely defining a standalone struct Buffer or setting its length to three does not reserve three payload elements. For an element type larger than one byte, check the multiply-and-add before computing sizeof *p + count * sizeof p->items[0]; the byte example’s addition-only guard is not enough for every element type.

3. sizeof and the payload offset are different facts

Ordinary sizeof(struct Buffer) does not count an intended runtime payload. The structure may contain trailing padding, and the flexible member’s offset need not equal that size. Include <stddef.h> for offsetof and size_t; query both instead of guessing a layout.

C17 · illustrative fragment
struct Buffer { size_t length; unsigned char data[]; };
size_t payload_offset = offsetof(struct Buffer, data);
size_t header_size = sizeof(struct Buffer);

After a successful checked allocation of sizeof *buffer + length for this byte member, at least length payload bytes are available. Padding can make more physical room available than the logical request. Continue using the recorded length, not an inferred spare capacity. With a logical length of zero, make no element accesses; a header-only allocation is not permission to use data[0] as application payload.

4. Copy the logical payload explicitly

Ordinary structure assignment does not clone the flexible array’s logical contents. Do not rely on incidental copying of bytes that overlap the fixed structure representation. Allocate another object of a checked size and copy the known payload separately. This example uses two distinct live allocations, so the byte-copy regions do not overlap.

Complete C17 program
#include <assert.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>

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

int main(void)
{
    size_t length = 3;
    if (length > SIZE_MAX - sizeof(struct Buffer)) return EXIT_FAILURE;
    struct Buffer *source = malloc(sizeof *source + length);
    if (source == NULL) return EXIT_FAILURE;
    struct Buffer *copy = malloc(sizeof *copy + length);
    if (copy == NULL) { free(source); return EXIT_FAILURE; }
    source->length = length;
    source->data[0] = 4;
    source->data[1] = 5;
    source->data[2] = 6;
    copy->length = source->length;
    if (length != 0) memcpy(copy->data, source->data, length);
    copy->data[0] = 9;
    assert(source->data[0] == 4 && copy->data[2] == 6);
    free(copy);
    free(source);
    return 0;
}

The fixed header length is copied as a value. The byte payload is copied with memcpy from <string.h>, only for a nonzero length in this pattern. Releasing the enclosing allocation releases its tail too. Do not separately free data, and do not keep interior pointers after release or successful replacement by realloc.

5. A flexible member has structural constraints

In C17, a structure with a flexible array member is restricted from being an ordinary member of another structure or an array element; related restrictions also cover unions containing such a structure. Do not generalize the design into freely nested variable-sized records. Standard initialization also does not provide the dynamically sized flexible payload through a normal member initializer; some compilers support extensions, which are separate from this baseline.

This buffer is a counted byte sequence, not automatically a C string. If the payload must contain a terminated string of length n, also reserve and check room for the terminator and write it. A length field describes your interface; it does not change allocation size, initialize bytes, or prove the stored count trustworthy.

Primary references and further reading

Before you move on

  • A flexible array member supports trailing elements after a structure’s fixed members.
  • Checked allocation arithmetic must provide storage for the intended tail.
  • Logical length, initialised payload, and actual capacity must stay consistent.
Keep these ideas separate
Base structure size / Tail capacity
sizeof the structure does not count an arbitrary runtime number of trailing elements.
Explain it in your own words

Which calculations and initialisations are needed before a flexible-array record can expose its payload?

Optional: say it aloud or keep a note. You can continue whenever you are ready.

Check your understanding

Optional. Answers are not saved or sent, and reading stays unrestricted.

Does setting a count field allocate space for a flexible array member?
Read the explanation for every choice
  1. Yes, the array grows automatically to match the count.

    A count assignment does not acquire storage.

  2. Yes, sizeof the header always includes any desired payload.

    The type’s fixed size does not supply arbitrary extra payload capacity.

  3. No. The allocation must separately provide sufficient checked capacity.

    ✓ Correct reasoning. Keep the count, allocation size, and bounds consistent; check size arithmetic before allocating.

C17

Ready for the next idea?

Mark this chapter as read whenever you feel ready.

CHAPTER 36 / 73

In this chapter

Flexible array members

Search all 73 chapters in both languages.EN + HG

Try “pointer”, “why int”, or “undefined behavior”.

Concepts connect. Follow your curiosity.↑ ↓ to explore · Enter to open
MAKE YOURSELF COMFORTABLE

Your reading space

Appearance

A clear canvas with balanced contrast.

Text size

100%
AA

Reading tools

Your data stays in this browser

Export a backup before changing browsers or replacing an older version of the reader.

YOUR PERSONAL MARGINS

My notebook

Saved on this device
A LITTLE CLARITY

The glossary

A starting meaning, then a chapter to go deeper.

A QUICK DEFINITION

A little clarity

Read the full explanation →

A thought worth keeping