[英]Why doesn't this code generate an error on using a variable array size?
The code below should generate an error, since there is no way that the compiler can know the array size during compilation. 下面的代码应该生成错误,因为在编译期间编译器无法知道数组大小。
int f;
std::cin >> f;
int c[f];
c[100] = 5;
I am compiling with gcc (Ubuntu 4.8.2-19ubuntu1) 4.8.2 and it doesn't just compile, but it runs somehow. 我正在使用gcc(Ubuntu 4.8.2-19ubuntu1)4.8.2进行编译,它不仅仅是编译,而是以某种方式运行。
How does it happen? 怎么会发生?
C99 accepts variable length arrays, and gcc accepts them as an extension in C90 and C++ . C99接受可变长度数组,gcc接受它们作为C90和C ++中的扩展 。
Using -pedantic
or -Wvla
turns this into a warning in C++ code, and -Werror=vla
turns it into an error. 使用
-pedantic
或-Wvla
将其转换为C ++代码中的警告,并且-Werror=vla
将其转换为错误。
C++ doesn't do array bounds checking. C ++不进行数组边界检查。 The
line c[100] = 5;
line c[100] = 5;
is equivalent to *(c + 100) = 5;
相当于
*(c + 100) = 5;
. 。 You are just telling the compiler to write to a memory location at a certain offset from another memory location.
您只是告诉编译器写入距离另一个内存位置的某个偏移量的内存位置。 If you enter anything less than 100 into your program, you will be overwriting some data on the stack.
如果在程序中输入少于100的内容,则会覆盖堆栈中的某些数据。 Depending on what the rest of your code does, this could cause a stack overflow, a "random" crash as some important piece of data is overwritten, or it could work correctly (and then start randomly crashing later when some seemingly unrelated change changes the memory layout).
根据代码的其余部分,这可能会导致堆栈溢出,“随机”崩溃,因为一些重要的数据被覆盖,或者它可以正常工作(然后当一些看似无关的更改改变时随后开始随机崩溃记忆布局)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.