Why does the following work? I thought that writing to an an index of a vector object beyond the end of the vector object would cause a segmentation fault.
#incl
Somebody implementing std::vector
might easily decide to give it a minimum size of 10 or 20 elements or so, on the theory that the memory manager likely has a large enough minimum allocation size that it will use (about) the same amount of memory anyway.
As far as avoiding reading/writing past the end, one possibility is to avoid using indexing whenever possible, and using .at()
to do indexing when you truly can't avoid it.
I find that I can usually avoid doing indexing at all by using range-based for
loops and/or standard algorithms for most tasks. For a trivial example, consider something like this:
int main() {
vector x(1);
x.push_back(1);
for (auto i : x)
cout << i << "\n";
}
.at()
does work, but I rarely find it useful or necessary--I suspect I use it less than once a year on average.