typestar

Flexible array members in C

An array of unknown length as the last member: one allocation for header and data.

#include <stdlib.h>
#include <string.h>

typedef struct {
    size_t len;
    char data[];
} Buffer;

Buffer *buffer_new(const char *text) {
    size_t n = strlen(text);
    Buffer *b = malloc(sizeof *b + n + 1);
    if (b == NULL) {
        return NULL;
    }
    b->len = n;
    memcpy(b->data, text, n + 1);
    return b;
}

void buffer_free(Buffer *b) {
    free(b);
}

How it works

  1. The empty brackets must come last in the struct.
  2. sizeof the struct excludes the flexible part.
  3. Allocate the header plus n elements in a single call.

Keywords and builtins used here

The run, in numbers

Lines
22
Characters to type
324
Tokens
104
Three-star pace
100 tpm

At the three-star pace of 100 tokens a minute, this run takes about 62 seconds.

Type this snippet

Step 5 of 5 in Unions & layout, step 5 of 13 in Unions, bitfields & undefined behavior.

← Previous Next →