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.
Step 1: For each variable size item, create a hidden variable containing a pointer to the array, and a hidden variable holding the size of the array. These may be optimisied away, assigned to registers etc. as any other variable.
Step 2: Allocate space for non-variable size items in the normal way.
Step 3: To process the declaration of the variable size item, evaluate the size and store it into the size variable. Calculate the space for the variable size item, taking into account alignment. Make space on the stack for the variable size item, then store a pointer to the location of the item into the hidden pointer variable.
Step 4: Use the hidden pointer variable to access array elements. Use the hidden size variable for the sizeof operator.
Here is one possible model. Think of
arr
as a (fixed-size) pointer to a stack-allocated array: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.