[英]Scope of variably sized array
Is this always going to run as expected? 这总是能按预期运行吗?
char *x;
if (...) {
int len = dynamic_function();
char x2[len];
sprintf(x2, "hello %s", ...);
x = x2;
}
printf("%s\n", x);
// prints hello
How does the compiler (GCC in my case) implement variably sized arrays, in each of C and C++? 编译器(在我的情况下为GCC)如何在C和C ++中的每一个中实现大小可变的数组?
No. x2
is local to the if
statement's scope and you access it outside of it using a pointer. 否
x2
在if
语句的作用域内是局部的,您可以使用指针在它之外访问它。 This results in undefined behaviour. 这导致不确定的行为。
By the way, VLAs have been made optional in C11 and had never been part of C++. 顺便说一下,VLA在C11中已成为可选属性,并且从未成为C ++的一部分。 So it's better to avoid it.
因此最好避免这种情况。
No, for two separate reasons: 否,原因有两个:
C++: The code isn't valid C++. C ++:该代码不是有效的C ++。 Arrays in C++ must have a compile-time constant size.
C ++中的数组必须具有编译时常量大小。
C: No, because the array only lives until the end of the block in which it was declared, and thus dereferencing x
is undefined behaviour. C:否,因为数组仅生存到声明它的块的末尾,因此取消引用
x
是未定义的行为。
From C11, 6.2.4/2: 从C11,6.2.4 / 2:
If an object is referred to outside of its lifetime, the behavior is undefined.
如果在其生存期之外引用对象,则行为是不确定的。
And 6.2.4/7 says that the variable-length array lives from its declaration until the end of its enclosing scope: 6.2.4 / 7表示可变长度数组从声明开始一直到其封闭范围的结尾:
For such an object that does have a variable length array type, its lifetime extends from the declaration of the object until execution of the program leaves the scope of the declaration.
对于确实具有可变长度数组类型的对象,其生存期从对象的声明开始,直到程序执行离开声明的范围为止。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.