A segmentation fault occurs in C++ when your program attempts to access memory not within the memory that the operating system allocated for your program. In other words, accessing memory that isn't yours.
According to the documentation for std::vector::operator[]
, under "Exception Safety", when accessing an index that is out of bounds, "the behavior is undefined". This means no checks are done.
Does this mean that a segmentation fault techically can occur? Yes. As the behaviour is undefined, it may just be that you are accessing memory that isn't yours, and a segmentation fault is signalled. As the behaviour is undefined, it might just be that the address you are trying to read is allocated to your program and can store 0
, garbage, or any other value.
In practice, an error generally will not be thrown if you're trying to access the [-1]
index of a vector or array, or if you go out of bounds. This is why a variety of undefined behaviour sanitizers, such as one made for Clang, are available to you. Upon undefined behaviour, these will raise an error and terminate your program.