C++ does not do out-of-bounds check for operator[]
for vector
s, 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, vector
s 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()
.