1

I have a strange problem regarding a vectors range. Take into account this code :

#include <iostream>
#include <vector>

using namespace std;
int main(){
  int n(0);
  vector<int> tab(n);
  tab[n] = 5;
  cout << tab[n];
}


The code displays a segfault when the size of the vector isn't declared, which makes sense. But it displays 5 when n has a given value, which DOES NOT work when n is 6 plus a multiple of 4 (i.e 6,10,14 etc). From theory the maximum index of an element must be tab.size()-1 so why does it happen?

Thank you in advance for answering!

Notmyne
  • 11
  • 1
  • 1
    TL;DR: Undefined behavior. Don't do it, don't be surprised if it works, or if it makes your pet squirrel pregnant. – Max Langhof Nov 21 '19 at 09:45

0 Answers0