As others have pointed out, VLAs make it really easy to overflow your stack frame. I'm not a compiler writer, but my understanding is that VLAs can also be a bugger to support (they are now optional in C2011). And their use is limited to block or function scope; you cannot use a VLA at file scope, and they can't have external linkage.
I wouldn't want to see VLA syntax go away, though; it comes in really handy when dynamically allocating multi-dimensional arrays where the inner dimensions are not known until runtime, such as:
size_t r, c;
// get values for r and c
int (*arr)[c] = malloc(r * sizeof *arr);
if (arr)
{
...
arr[i][j] = ...;
...
free(arr);
}
One contiguous allocation (and one corresponding free
), and I can subscript it as a 2D array. The alternatives usually mean piecemeal allocation:
size_t r, c;
...
int **arr = malloc(sizeof *arr * r);
if (arr)
{
for (i = 0; i < c; i++)
arr[i] = malloc(sizeof *arr[i] * c);
...
arr[i][j] = ...;
...
for (i = 0; i < c; i++)
free(arr[i]);
free(arr);
}
or using 1-d offsets:
int *arr = malloc(sizeof *arr * r * c);
if (arr)
{
...
arr[i * r + j] = ...;
...
free(arr);
}