The following programs demonstrate how VLAs can be used in some pretty cool ways in C. They allow creating dynamic array types, with information about the size of the array being known only at runtime.
- The first example shows how this kind of information can be attached to VLAs which are completely heap-allocated, and never touch the stack.
- In the second example, the information attached to the type of the array is used in combination with UBSan to check for out of bounds access to the array at runtime!
- Lastly, the third example demonstrates why we have to use this
weirdspecial syntax to correctly dereference and access pointers to VLAs.
Examples two and three make use of the fact that classic, fixed-size C arrays are interoperable with VLAs. That is, given a fixed-size array, we're able to pass it and its its size to a function that expects a VLA.