1

The following code

int x;
cin >> x;
int b[x];
b[5] = 8;
cout << sizeof(b)/sizeof(b[0]) << endl << b[5];

with x inputted as 10 gives the ouput:

10
8

which seems very weird to me because:

According to http://www.cplusplus.com/doc/tutorial/arrays/ we shouldn't even be able to initialize an array using a value obtained from cin stream.

NOTE: The elements field within square brackets [], representing the number of elements in the array, must be a constant expression, since arrays are blocks of static memory whose size must be determined at compile time, before the program runs.

But that's not the whole story! The same code with x inputted as 4 sometimes gives the output

Segmentation fault. Core dumped.

and sometimes gives the output:

4
8

What the heck is going on? Why doesn't the compiler act in a single manner? Why can I assign a value to an array index that is larger than the array? And why can we even initialize an array using variable in the first place?

user3142434
  • 305
  • 3
  • 15
  • 2
    I think this is what undefined behavior means. You can't tell what it'll do. – therainmaker Oct 01 '15 at 17:14
  • 3
    It is a C99 feature [but several compilers support in C++ as an extension](http://stackoverflow.com/a/25939282/1708801). Accessing an array out of bounds is undefined behavior, don't do it. – Shafik Yaghmour Oct 01 '15 at 17:16
  • @Shafik Yaghmour thanks, this message has helped me understand what's going on – user3142434 Oct 01 '15 at 17:33
  • @therainmaker It's not UB. It's required to be diagnosed. – Brian Bi Oct 01 '15 at 17:39
  • @Brian : What do you mean 'its required to be diagnosed'? – therainmaker Oct 01 '15 at 17:40
  • @therainmaker It means the compiler must issue a "diagnostic message" (which could be just a warning). Then again, I suppose if it compiles it anyway, technically it is undefined behaviour, since the standard doesn't define it. – Brian Bi Oct 01 '15 at 17:43
  • "My code has a bug, why does it do strange things?" Because it has a bug. Fix the bug and the mystery will go away. – David Schwartz Oct 01 '15 at 17:55

1 Answers1

2

I initially mentioned this as a comment, but seeing how no one has answered, I'm gonna add it here.

What you have demonstrated above is undefined behavior. It means that you can't tell what will the outcome be. As Brian adds in the comments, it will result in a diagnostic message (which could be a warning). Since the compiler would go ahead anyway, it can be called UB as it is not defined in the standard.

therainmaker
  • 4,253
  • 1
  • 22
  • 41