Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

No compilation error or run time error when index out of range of vector class?

Tags:

c++

vector

When I was using vector class, I found out that there is no compilation error or run time error when indexing out of range of a vector. The problem can be shown by the following code

#include <iostream>
#include <vector>

using namespace std;

int main(){

  vector<double> a(10,0.0);
  a[10]=10.0;
  cout<<"a[10]="<<a[10]<<"\n";
  cout<<"size of a is "<<a.size()<<"\n";
  return 0;
}

The result of running this code is

a[10]=10
size of a is 10

with no error reported. Another thing to notice is that a.size() still returns 10, although I can access a[10] successfully.

My question is that is there a way to let the program report an error when one tries to index out of the range of a vector?

like image 350
andy90 Avatar asked Dec 15 '22 17:12

andy90


1 Answers

This is by design. To offer maximum performance, operator[] does not check the argument for validity. Just like with naked arrays, accessing an element outside the bounds of a vector results in undefined behaviour.

...although I can access a[10] successfully...

This is a permissible manifestation of undefined behaviour. It is equally permissible for your code to throw an exception, to crash, to pass all your tests but then blow up in your customer's face, to launch a nuclear strike etc.

You could use std::vector::at(index) for bounds-checked access. It throws std::out_of_range if the index is not valid.

Bounds checking vs no bounds checking does not have to be an all-or-nothing proposition: see How to make std::vector's operator[] compile doing bounds checking in DEBUG but not in RELEASE and tools like Valgrind.

like image 131
NPE Avatar answered Jan 12 '23 01:01

NPE