When you attempt to access an element outside the bounds of a C-style array, you are invoking undefined behavior. This means that the language makes no guarantees about what will happen.
In practice, several things could occur:
Here's an example:
int main() {
int arr[3] = {1, 2, 3};
// Out of bounds access
std::cout << arr[5];
}
In this case, arr[5]
is accessing memory beyond the end of the array, which is undefined behavior.
To avoid this, always ensure your array accesses are within the valid bounds of the array. If you need runtime bounds checking, consider using std::vector
or std::array
instead, which offer .at()
for bounds-checked access.
Answers to questions are automatically generated and may not have been reviewed.
A detailed guide to working with classic C-style arrays within C++, and why we should avoid them where possible