Variable Length Arrays (VLA) were introduced in the C99 standard; prior to that, all array sizes had to be known at compile time. They allow declaring arrays whose size is determined by a variable known only at runtime.
Improper use of VLA leads to unhandled memory allocation errors (e.g., a too large array size can cause stack overflow), inability to pass VLA between different compilers (not all of them support it), and limited compatibility with older C and C++ standards. Debugging is also complicated by the fact that memory is allocated on the stack, not the heap, which is not always expected.
When using VLA, one must remember that they reside on the stack and cannot be global or static. It’s better to prefer dynamic arrays via malloc if flexibility and guaranteed interaction with C++ are needed. For compatibility, it is advisable to stick to static arrays or C90 standards if VLA support is not guaranteed.
Code Example:
#include <stdio.h> void process(size_t n) { int arr[n]; // VLA for(size_t i = 0; i < n; i++) arr[i] = i; for(size_t i = 0; i < n; i++) printf("%d ", arr[i]); } int main() { process(5); return 0; }
Key Features:
Can a static variable of variable length array be declared as static int arr[n]; inside a function?
No, static variables must have a defined size at compile time. Therefore static int arr[n]; with a variable size will cause a compilation error.
Will VLA be automatically freed when exiting a function?
Yes, VLA are placed on the stack and their memory is automatically freed when exiting a block/function, just like ordinary local variables.
Is it safe to allocate a VLA of very large size?
No, the stack size is limited (e.g., 1 MB or 8 MB). Attempting to allocate a large VLA will result in a runtime error (stack overflow).
We wrote cross-platform code using VLA, and the code did not compile on older or strictly configured compilers.
Pros:
Cons:
We used VLA only for local tasks and where a small size was guaranteed, for larger arrays — malloc/free.
Pros:
Cons: