#include /**************************************************** * This program demonstrates what may happen when * you access entries outside the bounds of an array. * * IMPORTANT: * * Accessing an array outside its bounds results in * undefined behavior. Nothing demonstrated by this * program is guaranteed by C++. * * In one particular execution of this program, the * compiler happened to allocate memory approximately * as follows: * * 0x7ff...0dc n <- initially 91 * 0x7ff...0e0 array[0] * 0x7ff...0e4 array[1] * 0x7ff...0e8 array[2] * 0x7ff...0ec array[3] * 0x7ff...0f0 array[4] * 0x7ff...0f4 array[5] * 0x7ff...0f8 array[6] * 0x7ff...0fc array[7] * 0x7ff...100 array[8] * 0x7ff...104 array[9] * 0x7ff...108 m <- initially 42 * * With this particular arrangement, it appeared that * * array[-1] * * accessed the memory occupied by n, while * * array[10] * * accessed the memory occupied by m. * * Again, this is not guaranteed. A different compiler, * different compiler options, or even another execution * of the same program may produce different results. * * The only valid indices for array are 0 through 9. ****************************************************/ int main() { std::cout << "Initializing 'm' with the value 42..." << std::endl; int m{ 42 }; int array[10]; std::cout << "Initializing 'n' with the value 91..." << std::endl; int n{ 91 }; std::cout << " m = " << m << std::endl; std::cout << " n = " << n << std::endl; std::cout << std::endl; std::cout << " &m = " << &m << std::endl; std::cout << " array = " << array << std::endl; std::cout << " &n = " << &n << std::endl; std::cout << std::endl; std::cout << "Assigning array[k] the value k" << std::endl; std::cout << "for k = -1, 0, 1, ..., 10." << std::endl; // WARNING: // // The assignments for k == -1 and k == 10 // access memory outside the array and therefore // result in undefined behavior. for ( int k{ -1 }; k <= 10; ++k ) { array[k] = k; } std::cout << std::endl; std::cout << " m = " << m << std::endl; std::cout << " n = " << n << std::endl; std::cout << std::endl; std::cout << "Assigning 'm' the value 150..." << std::endl; m = 150; std::cout << "Assigning 'n' the value 250..." << std::endl; n = 250; std::cout << std::endl; // WARNING: // // Similarly, reading array[-1] and array[10] // results in undefined behavior. for ( int k{ -1 }; k <= 10; ++k ) { std::cout << " array[" << k << "] = " << array[k] << std::endl; } return 0; }