0

When I try to run the C++ code below it does not return an out of bounds error. Infact it just runs fine and gives me 11 as output. Why is that?

#include<iostream>
#include<vector>
using namespace std;
int main()
{
    vector< vector<int> > Matrix(10, vector<int>(10));
    Matrix[9][10000]=11;
    cout<<Matrix[9][10000];
    return 0;
}

1 Answers1

1

C++ does not do out-of-bounds check for operator[] for vectors, so accessing out-of-bounds element is undefined behavior. It may well run without any problems, or may crash your program or even format your hard drive.

In fact, for small misses (like a couple of elements, etc) the access can fall into the memory owned by your program, so the program will most probably run not noticing it. (Provided you do not overwrite other important variables.) In particular, vectors usually reserve more memory than they really use, so a small miss with vector will most probably fall into allocated-but-not-used memory and will run ok.

In this particular case correct running is quite strange as it is a really far away from bounds, but I think an optimizer may optimize away array access at all. It can see the the same element is assigned and printed, and can remove asignment and print.

To do proper bound check, you can use .at().

Petr
  • 9,812
  • 1
  • 28
  • 52