Not only, as you correctly say
VLAs are not officially supported in C++.
but they also were relegated to "optional feature" since C11 (though they were added only in C99!). This is actually a reason for not using them, in the purpose of having portable code.
Its memory allocation details are unfortunately implementation dependant. They are are usually allocated in the stack by most compilers as automatic storage variables (according to my reasearch and to my personal experience), but can also be allocated in the heap.
Having arrays allocated in the stack can lead to stack overflow issues, especially in embedded environment. I suggest visiting this question (about VLAs not being supported in C++ standards); in particular, it is really interesting this answer, by @Quuxplusone (enphasis is mine):
Variable-length arrays in C99 were basically a misstep. In order to support VLAs, C99 had to make the [...] concessions to common sense.
Less importantly in the C++ world, but extremely important for C's target audience of embedded-systems programmers, declaring a VLA means chomping an arbitrarily large chunk of your stack. This is a guaranteed stack-overflow and crash. (Anytime you declare int A[n]
, you're implicitly asserting that you have 2GB of stack to spare. After all, if you know "n is definitely less than 1000 here", then you would just declare int A[1000]
.
As far as I can see, their main advantage is having arrays of variable length with local scope, something that cannot be achieved with its alternatives:
/* Fixed length array, either global or local */
int arr[100];
/* Dynamic allocation */
int * arr = malloc (100 * sizeof (int));
In most cases, anyway, the developer either
- Knows what is the maximum size that VLA can have. So why not allocating it statically with a fixed length?
- Has no control on the maximum size, so they will have to perform a sanity check to avoid stack overflows. So why not limiting its size with a fixed length allocation?