简体   繁体   中英

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.

How does it happen?

C99 accepts variable length arrays, and gcc accepts them as an extension in C90 and C++ .

Using -pedantic or -Wvla turns this into a warning in C++ code, and -Werror=vla turns it into an error.

C++ doesn't do array bounds checking. The line c[100] = 5; is equivalent to *(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. 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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM