Array Out-Of-Bounds Error
/* * This program will blow up on some systems. It's more interesting * when it doesn't */ #include <iostream> #include <array> int main() { // Declare an array of size four, and some other variables. int a; std::array<int,4> arr; int z; int m; // Treat the array as if it were size ten and see what happens a = 99; z = 100; for(m = 0; m < 10; m++) arr[m] = 2*m - 1; for(m = 0; m < 10; m++) std::cout << arr[m] << " "; std::cout << std::endl << a << " " << z << std::endl; }

C++ (like plain C) does not check array bounds. This program references the array far out of bounds, but it does not throw any exception. What it does is attempt to complete the subscripting operations where the subscript specifies, a location outside the array. The actual results of this madness will vary with the compiler and operating system which gets to perform them.

One of the primary design goals of C is efficiency. Checking the bounds takes time, so we're not going to do it for you. If you need to check them, either checks yourself or use the at method (see below).

Always be very careful about bounds-checking arrays in C++. The results of errors can be quite obscure and difficult to debug.