C++ has a notion of undefined behavior. Accessing a vector out-of-bounds is a typical example of undefined behavior (because vector::operator[]
performs no bounds checking). Nothing meaningful can be said about the outcome of the program.
But to explain what probably happens...
A vector
is a class
that usually contains a pointer to a heap-allocated array and its size (the "capacity").
An empty vector has a null pointer value. Dereferencing a null pointer often immediately leads to a segfault because there's no virtual memory region allocated at address 0.
On the other hand, a vector of capacity 2
points to an array of size 2
. Writing past it is often possible, you will simply overwrite heap memory that happens to reside immediately after that array. This is called a heap buffer overflow. In a simple program it may appear to work fine. But in a larger program nothing good will happen somewhere further down the code.