Suppose I have the following function, which makes use of a variable-length array:
void func(int size)
{
int var1;
int arr[size];
int var2;
...
}
How does the compiler determine the address of var2
?
The only way that I can think of is by placing arr
after var1
and var2
.
But in that case, what if there were several variable-length arrays?
Placing all of them after the "normal" variables would only help resolving the address of the first one.
My implicit assumption here is that all the local variables (including VLAs) are allocated on the stack.
I realize that it is not defined by the C99 standard, so the question is in essence about compilation.
Here is one possible model. Think of arr
as a (fixed-size) pointer to a stack-allocated array:
int var1;
int *arr = alloca(sizeof(int) * size);
int var2;
Note how the (relative) location of the three variables does not change with size
. This model readily generalizes to multiple VLAs.
Note that this is only an example. Each compiler is free to implement VLAs however it pleases. If you want to know what your compiler does, look at the generated assembly code.