v010dya
v010dya

Reputation: 5848

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?

Upvotes: 7

Views: 204

Answers (2)

Tom Anderson
Tom Anderson

Reputation: 111

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).

Upvotes: 1

BoBTFish
BoBTFish

Reputation: 19767

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.

Upvotes: 13

Related Questions