by enriquto · 5y ago · 0 comments
void f(int n, ...)
{
float *t = malloc(n * sizeof*t);
// do stuff with t[i]
free (t);
}
with the following semantically equivalent code void f(int n, ...)
{
float t[n];
// do stuff with t[i]
}
Today, this is not a good idea for large arrays because, unfortunately, many C implementations put VLA in the stack. I hope that by keeping VLA in the standard language, future C implementations will get to favor this usage.Notice that VLA are not more dangerous or risky than recursion. The exact same argument that you use against VLA can be used against recursion. Are you against recursive functions in C? Of course, you wouldn't traverse a long array using recursion, but if you are careful that the depth of recursion is logarithmic with the array size (e.g. as in binary search), then it is perfectly safe and reasonable to use recursion. The same thing with VLA. If you are sure that n is 2,3 or at most 4 there's no reason to avoid VLA due to stack scare, and they may make your code much simpler, clearer and better.
On the other hand, VLA are useful even if you do not use them to allocate memory. Pointers to vla can be used for many things, for example accessing a one-dimensional array (allocated by a single call to malloc) using two indices as if it was a 2d array.
However they have backtracked on their position regarding supporting C on Windows, so latest MVSC does support C11 and C17.