Is it safe to take address of an out of bounds vector index?

Viewed 90

In C++ Primer 5th edition it is mentioned that you can take the address of the non-existent element one past the last element of an array (so long as you don't de-reference it).

int arr[] = {0,1,2,3,4,5,6,7,8,9};
int *e = &arr[10]; // 10 is 1 past the end.

For std::vector, does indexing into the vector with the [] operator and taking a reference have the same guarantee as array that it won't crash?

vector<int> vec(10, 0);
int *e = &vec[10];

I do understand there's little use-case for this since we have end() iterators and all that.

1 Answers

It's undefined behaviour. The definition of vec[10] is

*(vec.begin() + 10)

which is dereferencing an past-the-end iterator. Furthermore

Values of an iterator i for which the expression *i is defined are called dereferenceable. The library never assumes that past-the-end values are dereferenceable.

Related