Originally Posted by
c99tutorial
This is not correct. Creating an array of a size not known at compile time is known as a VLA (variable length array) and performs a stack allocation.
Your correction is also inaccurate. While it is true that the size of a VLA is determined at run time, its size cannot subsequently change.
I've lost track of the number of times folks have expected samples like these to work.
Code:
/* Danger: code with undefined behaviour here */
int main()
{
int i, n;
int x[n];
n = some_value_obtained_at_runtime();
for (i = 0; i < n; ++) x[i] = something();
}
or
Code:
/* Danger: code with undefined behaviour here */
int main()
{
int i, n;
n = some_value_obtained_at_runtime();
int x[n];
for (i = 0; i < n; ++) x[i] = something(); /* this is actually okay */
n = some_larger_value_obtained_at_runtime();
for (i = 0; i < n; ++) x[i] = something(); /* this is not, as the array has not resized */
}
Technically, C does not support a notion of stack either, but that's a philosophical point. Stack and heap and other things are implementation specifics. There is nothing stopping the compiler from implementing VLAs under the covers using dynamic memory allocation (malloc() when the array is created, free() to release it).