Question

I learned something interesting today: if I have a standard vector v and I run code like:

std::vector<float> v;
for (int i = 0; i < 2; i++) v.push_back(2.);

if I call v[2] I will not get a segmentation fault, because the operator[] does not do bounds checking. I was getting some absurdly small number, but I was curious what the default behavior of push_back is and what I should expect from overflowing a vector bounds. I would assume it would have to allocate more space than just the next float. How much? Is this in the standard, or is it compiler-specific?

Was it helpful?

Solution

I learned something interesting today

So it's time to learn something even more interesting: your code has Undefined Behavior, because the precondition for using the subscript operator is that the index is smaller than the size of the vector.

Per Table 101 of the C++11 Standard, the expression a[n] is equivalent to *(a.begin() + n). Since v.begin() + 2 is an iterator to a position beyond the end of the container v, dereferencing it results in Undefined Behavior.

OTHER TIPS

if I call v[2] I will not get a segmentation fault, because the operator[] does not do bounds checking

Those two aren't related like this...

Your code invokes undefined behavior, so it can do anything.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top