7

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?

1

2 Answers 2

13

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks. I didn't think about looking at C standards.
1

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

2 Comments

Your description is correct, but not really relevant to the question which is really about why the line int c[f]; compiles when f is not a compile-time constant..
I did recognise that part. I just added it to make sure that i was actually creating an array at all. But i think that this can be useful to other people who will come across this question.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.