C++ – Overcoming wrong memory allocation in C++


In a C++ program I write:

using namespace std;
int main()
   vector<int> a;
   for( int i = 0 ; i < 10 ; i++ ) {
       cout << a[i] << " ";

   return 0;

this program prints the correct value of a[0] (because it is allocated) but also prints values at the rest of the 10 locations instead of giving a segmentation fault.

How to overcome this while writing your code? This causes problems when your code computes something and happily accesses memory not meant to be accessed.

Best Solution

Use this:


at() will throw an out_of_range exception if the index is out of bounds.

The reason that operator [] doesn't do a bounds check is efficiency. You probably want to be in the habit of using at() to index into a vector unless you have good reason not to in a particular case.