Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does GCC implement variable-length arrays?

How does GCC implement Variable-length arrays (VLAs)? Are such arrays essentially pointers to the dynamically allocated storage such as returned by alloca?

The other alternative I could think of, is that such an array is allocated as last variable in a function, so that the offset of the variables are known during compile-time. However, the offset of a second VLA would then again not be known during compile-time.

like image 760
box Avatar asked Jan 17 '14 09:01

box


People also ask

How do variable length arrays work in C?

In computer programming, a variable-length array (VLA), also called variable-sized or runtime-sized, is an array data structure whose length is determined at run time (instead of at compile time). In C, the VLA is said to have a variably modified type that depends on a value (see Dependent type).

How is VLA implemented?

VLA works by placing the array in the stack - stackoverflow.com/questions/2034712/variable-length-arrays. That is also what I see when checking the assembly output generated by gcc when using a VLA, no call to malloc . But it might depend on the actual implementation. This is an open source project.

How do you use variable length arrays?

A variable length array can be used in a typedef statement. The typedef name will have only block scope. The length of the array is fixed when the typedef name is defined, not each time it is used. A function parameter can be a variable length array.

How do VLA work?

How does it work? The VLA is an interferometer; this means that it operates by multiplying the data from each pair of telescopes together to form interference patterns.


1 Answers

Here's the allocation code (x86 - the x64 code is similar) for the following example line taken from some GCC docs for VLA support:

char str[strlen (s1) + strlen (s2) + 1]; 

where the calculation for strlen (s1) + strlen (s2) + 1 is in eax (GCC MinGW 4.8.1 - no optimizations):

mov edx, eax sub edx, 1 mov DWORD PTR [ebp-12], edx mov edx, 16 sub edx, 1 add eax, edx mov ecx, 16 mov edx, 0 div ecx imul    eax, eax, 16 call    ___chkstk_ms sub esp, eax lea eax, [esp+8] add eax, 0 mov DWORD PTR [ebp-16], eax 

So it looks to be essentially alloca().

like image 186
Michael Burr Avatar answered Sep 19 '22 06:09

Michael Burr