[Solved] Can I access a location in vector which I haven’t declared? [duplicate]


The answer can be read in the C++ reference.

Here you can read that no boundary check will be done and no new element will be inserted. You simply have undefined behaviour.

So, in moredetail:

  • using an index operator with an index bigger than the size of the vector, will not increase the size of the vector and add new elements.
  • Using an out of bound index that is bigger than the vectors size, will simply access a memory location, which does not belong to the vector.
  • Reading such a position will mostly give a random value or better set, an undefined value. This will usually not harm your program, except that you get undefined values back.
  • Writing to an out of bounds value usually is a very severe problem, because you are overwriting memory, which you do not won. Very dangerous.

If you want to have boundary checking, then use vectors at-function.

6

solved Can I access a location in vector which I haven’t declared? [duplicate]