0
class array {
    public:
        int arr[];

        array() {
            arr[0] = 1;
            arr[100] = 2;
        }
};

int main() {
    array a;
    cout << a.arr[0] << a.arr[100] << endl;
    return 0;
}

I was expecting a segmentation fault on running the above code. However, it printed the correct output even though I have not mentioned array size. What is the reason for this?

bornfree
  • 2,308
  • 1
  • 23
  • 33
  • 1
    Undefined behaviour includes appearing to work. – Alan Stokes Oct 06 '15 at 06:32
  • 1
    `cout << arr[0] << arr[100] << endl;` isn't this line give you a build error? – Nayana Adassuriya Oct 06 '15 at 06:35
  • "Why can I climb mountains even though I have not put my climbing harness?" – el.pescado - нет войне Oct 06 '15 at 06:36
  • c++ does not check array out of bounds. And as all have said it's undefined behavior. Hope it helps. – Abhishek Ranjan Oct 06 '15 at 06:36
  • @el.pescado - Oh yes . sorry. Its a typo. – bornfree Oct 06 '15 at 06:38
  • Very close the question with [that](http://stackoverflow.com/a/25636788/841108) answer, which applies here as well – Basile Starynkevitch Oct 06 '15 at 06:40
  • 3
    The code isn't valid C++. `arr` needs to have a complete type. See [Array data members declared with no size](http://stackoverflow.com/questions/26614439/array-data-members-declared-with-no-size). – juanchopanza Oct 06 '15 at 06:44
  • 1
    With the right setting, a good compiler would warn you. See [here](http://coliru.stacked-crooked.com/a/7b014ecaaadc6ec0). Indeed, as juanchopanza said, this is illegal in C++. Additional [interesting reading](http://stackoverflow.com/q/4778552/2436175). – Antonio Oct 06 '15 at 06:47
  • @juanchopanza - I compiled the code using g++. The thread that you mentioned states that it may be a bug in the compiler. So is it a g++ bug ? – bornfree Oct 06 '15 at 08:59
  • @bornfree It could be a bug, but it is probably an "extension". It is valid in current C, and gcc often ports some C features into C++ as extensions. But you can control standard adherence with compiler flags. – juanchopanza Oct 06 '15 at 09:04

1 Answers1

5

What you get is Undefined Behavior.

Reading / Writing to unallocated memory does not automatically generate segmentation fault(s), but it is of course "bad practice" and should be avoided.

It's impossible to tell exactly what will happen with such code, where that array will be addressed or what is already there and hence - Undefined Behavior.

Note: As mentioned by @juanchopanza, the code as it is is illegal in C++ because arr is an incomplete type. Your compiler might (and obviously does) ignore this due to default settings, but a legal code that would demonstrate the same behavior is either:

class array {
    public:
        int *arr;
// ...

or

class array {
    public:
        int arr[1];
// ...
Amit
  • 45,440
  • 9
  • 78
  • 110