为什么 GCC 允许可变大小数组的静态内存分配?
Why is GCC allowing static memory allocation of a variable sized array?
我写了一个简单的代码,它接受一个整数作为用户输入并分配一个可变大小的数组。
#include <stdio.h>
int main(){
int n, i;
scanf("%d", &n);
int arr[n];
for(i=0; i<n; i++){
arr[i] = i;
}
for(i=0; i<n; i++){
printf("%d\t", arr[i]);
}
return 0;
}
以上代码完美运行(如果数组大小不是很大,则在 2,150,000 左右给出段错误)。这怎么可能呢?我认为这应该使用动态内存分配来完成,因为数组大小是可变的。
我对内存分配的整个概念都动摇了。请解释在什么条件下允许这样做(应该是法律代码)。
从标准的 ISO C99 版本开始,允许使用可变长度自动数组,
这是引用自 2011 C 标准,6.7.5.2 数组声明符:
If the size is not present, the array type is an incomplete type. If
the size is * instead of being an expression, the array type is a
variable length array type of unspecified size, which can only be used
in declarations with function prototype scope.
If the size is an expression that is not an integer constant
expression: if it occurs in a declaration at function prototype scope,
it is treated as if it were replaced by *; otherwise, each time it is
evaluated it shall have a value greater than zero. The size of each
instance of a variable length array type does not change during its
lifetime.
我写了一个简单的代码,它接受一个整数作为用户输入并分配一个可变大小的数组。
#include <stdio.h>
int main(){
int n, i;
scanf("%d", &n);
int arr[n];
for(i=0; i<n; i++){
arr[i] = i;
}
for(i=0; i<n; i++){
printf("%d\t", arr[i]);
}
return 0;
}
以上代码完美运行(如果数组大小不是很大,则在 2,150,000 左右给出段错误)。这怎么可能呢?我认为这应该使用动态内存分配来完成,因为数组大小是可变的。
我对内存分配的整个概念都动摇了。请解释在什么条件下允许这样做(应该是法律代码)。
从标准的 ISO C99 版本开始,允许使用可变长度自动数组,
这是引用自 2011 C 标准,6.7.5.2 数组声明符:
If the size is not present, the array type is an incomplete type. If the size is * instead of being an expression, the array type is a variable length array type of unspecified size, which can only be used in declarations with function prototype scope.
If the size is an expression that is not an integer constant expression: if it occurs in a declaration at function prototype scope, it is treated as if it were replaced by *; otherwise, each time it is evaluated it shall have a value greater than zero. The size of each instance of a variable length array type does not change during its lifetime.