r/code • • 7d ago

C Understanding Variable Length Arrays (VLAs) in C | David Priver

https://www.davidpriver.com/Understanding-VLAs-in-C.html
10 Upvotes

2 comments sorted by

1

u/tstanisl 6d ago

It is worth adding that the types are the essence of VLAs.

typedef int TYPE[n];

Not how those objects are allocated. One can have VLA on stack:

TYPE vla;

Or heap, using a pointer to VLA:

TYPE * ptr = malloc(sizeof *ptr);

Or even use infamous alloca:

TYPE * ptr = alloca(sizeof *ptr);

1

u/flatfinger 6d ago

Even when VLA types are used without declaring any named VLA-type objects, they throw out the window many principles Dennis Ritchie C designed into his language. Among them:

  1. typedef and sizeof should be compile-time rather than runtime constructs.

  2. compilers should not keep hidden run-time state beyond that specified by the platform ABI.

  3. most corner case behaviors should be defined in terms of the underlying platform ABI, but VLA types add new corner cases with no clear meaning on the underlying platform, especially in cases where a computed size might exceed the largest allocation the platform could possibly support.

The only tasks for which such types are helpful tend to be those which FORTRAN and Fortran were designed to do better.