💾 SuperFloppies Place! 💾

Variable Length Array in C

This example compiles using gcc 8.2.0 using the C99 language implementation.

Command line used: gcc -std=gnu99 -o vla vla.c

Changelog

Code

/*
 * Variable-length array example.
 */
#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>

typedef struct vla_t vla_t;

struct vla_t {
        uint32_t size;
        uint8_t  data[];
};

int
main(int argc, char *argv[]) {
        uint32_t tlen = 1024;

        if(argc > 1) {
                tlen = strtol(argv[1], NULL, 10);

                printf("tlen = %u\n", tlen);
                if((tlen == 0) || (tlen > 0x100000)) tlen = 1024;
        }

        vla_t *mem = calloc(1, sizeof(vla_t) + tlen);
        mem->size = tlen;

        printf("Variable array located at %p, is %u bytes", mem->data, tlen);

        free(mem);
        return 0;
}

Now, if I’m misunderstanding what a “variable length array” is, this could explain why I would be surprised that it takes C code longer to work with one. To me, it just looks like a memory region on the heap.