简体   繁体   English

为什么这段代码在使用变量数组大小时不会产生错误?

[英]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.

相关问题 为什么这段代码不会产生编译错误? - Why doesn't this code generate compilation errors? 为什么这不能推断出数组大小? - Why doesn't this deduce array size? 为什么我们在vs代码中写C++代码时不能通过一个变量来定义数组大小? - Why can't we define the array size by a variable when we write C++ code in vs code? 如何生成一个以变量为大小的数组? - How to generate an Array with a variable as size? 为什么我的代码无法正确生成素数 - Why doesn't my code generate the prime numbers correctly 为什么局部变量不会隐藏数组定义中的全局变量 - why local variable doesn't hide the global variable in array definition 为什么编译器没有在参数中传递数组char * arr []的大小? - Why compiler doesn't pass size of array char *arr[] in parameters? 声明大小为整数变量的数组时,为什么会出现编译器错误? - Why is there a compiler error, when declaring an array with size as integer variable? 永远不要在PIMPL中提供析构函数(使用boost scoped_ptr),g ++(4.6.1)不会产生编译错误,为什么? - Never provide destructor in the PIMPL(using boost scoped_ptr), the g++(4.6.1) doesn't generate compile error, Why? 为什么堆栈中没有可变大小的数组? - Why no variable size array in stack?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM