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?

Shafik Yaghmour
  • 154,301
  • 39
  • 440
  • 740
v010dya
  • 5,296
  • 7
  • 28
  • 48
  • See [Does “int size = 10;” yield a constant expression?](http://stackoverflow.com/q/21273829/1708801) for a lot more details on this topic. – Shafik Yaghmour Apr 08 '15 at 09:31

2 Answers2

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.

BoBTFish
  • 19,167
  • 3
  • 49
  • 76
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).

Tom Anderson
  • 111
  • 3
  • 4
    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.. – BoBTFish Apr 08 '15 at 07:54
  • 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. – v010dya Apr 08 '15 at 07:54