问题描述
GCC 如何实现可变长度数组 (VLA)?这样的数组本质上是指向动态分配的存储(例如 alloca 返回)的指针吗?
How does GCC implement Variable-length arrays (VLAs)? Are such arrays essentially pointers to the dynamically allocated storage such as returned by alloca?
我能想到的另一种选择是,将这样的数组分配为函数中的最后一个变量,以便在编译时知道变量的偏移量.然而,第二个 VLA 的偏移量将在编译时再次未知.
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.
推荐答案
以下示例行的分配代码(x86 - x64 代码类似)来自 一些用于 VLA 支持的 GCC 文档:
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];
strlen (s1) + strlen (s2) + 1
的计算在 eax
中(GCC MinGW 4.8.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
所以它看起来本质上是alloca()
.
So it looks to be essentially alloca()
.
这篇关于GCC是如何实现变长数组的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!