Reading history

Flexible Array Members and Variable Length Arrays in C

6 min read 2 views

Use C flexible array members to allocate a struct and its data in one block, and variable length arrays for run-time sizes, with their risks.

C99 added two features for data whose size is only known while the program runs. A flexible array member lets the last member of a struct be an array with no fixed size, so a header and its data can live in a single block of memory. A variable length array (VLA) is an array whose length is a run-time value, such as int a[n]. Both are useful, and both have rules you need to know.

In this lesson you will learn

  • Declaring a struct with a flexible array member
  • Allocating the struct and its array with one malloc
  • Why sizeof does not include the flexible part
  • Creating VLAs and passing variable-size 2D arrays to functions
  • The risks of VLAs and when to avoid them

You should know structures, dynamic memory allocation and the sizeof operator.

Flexible Array Members

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

/* A flexible array member: the last member has no size */
typedef struct {
    char name[20];
    int count;
    int scores[];           /* storage comes from the same malloc */
} Student;

Student *make_student(const char *name, const int *scores, int count) {
    Student *s = malloc(sizeof *s + count * sizeof s->scores[0]);
    if (!s) return NULL;
    snprintf(s->name, sizeof s->name, "%s", name);
    s->count = count;
    memcpy(s->scores, scores, count * sizeof s->scores[0]);
    return s;
}

double average(const Student *s) {
    int total = 0;
    for (int i = 0; i < s->count; i++) total += s->scores[i];
    return s->count ? (double)total / s->count : 0.0;
}

int main(void) {
    int a[] = {78, 85, 91};
    int b[] = {66, 72, 80, 88, 95};
    Student *s1 = make_student("Ayesha", a, 3);
    Student *s2 = make_student("Tanvir", b, 5);
    if (!s1 || !s2) { free(s1); free(s2); return 1; }

    printf("sizeof(Student) = %zu (the scores are not counted)\n", sizeof(Student));
    printf("%s: %d scores, average %.2f\n", s1->name, s1->count, average(s1));
    printf("%s: %d scores, average %.2f\n", s2->name, s2->count, average(s2));

    free(s1);               /* one free releases the struct and its scores */
    free(s2);
    return 0;
}

Output

sizeof(Student) = 24 (the scores are not counted)
Ayesha: 3 scores, average 84.67
Tanvir: 5 scores, average 80.20
  • int scores[]; must be the last member, and the struct needs at least one other member before it.
  • sizeof(Student) is 24 bytes: the 20-byte name and the 4-byte count. The flexible array adds nothing, because its size is not known.
  • make_student allocates sizeof *s + count * sizeof s->scores[0] bytes, room for the header plus exactly the scores needed. Ayesha’s block holds 3 scores and Tanvir’s holds 5.
  • Because everything is in one block, a single free releases it all, and the scores sit right next to the header in memory, which is fast to access.
  • snprintf(s->name, sizeof s->name, "%s", name) copies the name safely; a longer name would be cut off rather than overflow the 20-byte field.
  • The alternative, a separate int *scores pointer, needs two allocations and two frees.

Variable Length Arrays

#include <stdio.h>

/* Variable length arrays (VLAs): the size is known only at run time */
double row_average(int cols, const int row[cols]) {
    int sum = 0;
    for (int c = 0; c < cols; c++) sum += row[c];
    return (double)sum / cols;
}

void fill_table(int rows, int cols, int t[rows][cols]) {
    for (int r = 0; r < rows; r++)
        for (int c = 0; c < cols; c++)
            t[r][c] = (r + 1) * (c + 1);
}

int main(void) {
#ifdef __STDC_NO_VLA__
    puts("This compiler does not support VLAs");
#else
    int n = 5;                      /* imagine this came from the user */
    int squares[n];                 /* a VLA on the stack */
    for (int i = 0; i < n; i++) squares[i] = i * i;
    printf("sizeof squares = %zu bytes (worked out at run time)\n", sizeof squares);

    int rows = 3, cols = 4;
    int table[rows][cols];
    fill_table(rows, cols, table);
    for (int r = 0; r < rows; r++) {
        for (int c = 0; c < cols; c++) printf("%3d", table[r][c]);
        printf("   average %.2f\n", row_average(cols, table[r]));
    }
#endif
    return 0;
}

Output

sizeof squares = 20 bytes (worked out at run time)
  1  2  3  4   average 2.50
  2  4  6  8   average 5.00
  3  6  9 12   average 7.50
  • int squares[n]; creates an array on the stack whose length comes from the variable n. Even sizeof squares is worked out at run time: 5 × 4 = 20 bytes.
  • In a parameter list such as int t[rows][cols], the sizes come from earlier parameters. This lets one function handle 2D arrays of any shape with ordinary t[r][c] indexing.
  • In C11 and later, VLAs are an optional feature. A compiler without them defines __STDC_NO_VLA__, and the #ifdef lets the program report that instead of failing to compile. GCC and Clang support VLAs; Microsoft’s compiler does not.
  • VLAs live on the stack, which is small, often 1 to 8 MB. A large or user-controlled n can overflow it and crash the program with no chance to recover. For big or untrusted sizes, use malloc.

Which Feature When?

NeedUse
A record with a variable-length list inside, such as a packet or a student with any number of scoresFlexible array member + malloc
A small temporary array sized at run timeVLA (if your compiler supports it)
Functions that accept 2D arrays of any sizeVLA parameters int a[r][c]
Large or untrusted sizesmalloc, never a VLA

Common Mistakes

  1. Allocating only sizeof(Student) for a struct with a flexible array, leaving no room for the array.
  2. Copying such a struct with =. Only the fixed part is copied; use memcpy with the full size.
  3. Putting a struct with a flexible array member inside an array or another struct. This is not allowed, because its size is unknown.
  4. Making a VLA of size 0 or from unchecked input. A size of zero is undefined behaviour, and a huge size overflows the stack.

Practice Exercises

Exercise 1. Define Message with a size_t len and a flexible char text[], and write Message *make_message(const char *s).

Show answer
typedef struct {
    size_t len;
    char text[];
} Message;

Message *make_message(const char *s) {
    size_t len = strlen(s);
    Message *m = malloc(sizeof *m + len + 1);
    if (!m) return NULL;
    m->len = len;
    memcpy(m->text, s, len + 1);   /* includes the '\0' */
    return m;
}

Exercise 2. Write int trace(int n, const int m[n][n]) that sums the diagonal of any square matrix.

Show answer
int trace(int n, const int m[n][n]) {
    int sum = 0;
    for (int i = 0; i < n; i++) sum += m[i][i];
    return sum;
}

Frequently Asked Questions

What is the “struct hack”?

Before C99, programmers declared the last member as int data[1] and allocated extra space after it. It usually worked, but going past the declared size was technically undefined. The flexible array member is the standard, safe replacement.

Does C++ have flexible array members or VLAs?

Standard C++ has neither, although some compilers accept them as extensions. C++ code normally uses std::vector instead.

Summary

  • A flexible array member is a sizeless last array in a struct.
  • Allocate header plus data in one malloc; release it with one free.
  • VLAs have run-time sizes but live on the limited stack.
  • VLAs are optional since C11; prefer malloc for large or untrusted sizes.

Next: Random Numbers in C.

Lessons are also marked complete when you click Next.

Leave a Reply

Your email address will not be published. Required fields are marked *