Why does this code not generate an error when using the size of an array of variables?

An error should appear in the code below, since the compiler cannot know the size of the array at compile time.

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 not only compiles, but works somehow.

How does this happen?

+7
c ++ gcc variable-length-array
source share
2 answers

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 into C ++ code, and -Werror=vla turns it into an error.

+13
source share

C ++ does not check the bounds of an array. line c[100] = 5; equivalent to *(c + 100) = 5; . You simply tell the compiler to write to a memory location with a specific offset from another memory location. If you enter anything less than 100 into your program, you will overwrite some data on the stack. Depending on what the rest of your code is doing, this may lead to a stack overflow, an β€œaccidental” failure, as some important parts of the data will be overwritten, or it may work correctly (and then start random failures later when some seemingly , unrelated changes will change the memory layout).

+1
source share

All Articles