Chapter 4. Index Out of Bounds
There are several ways in C++ to create an array of objects of some
type T. Three common methods are:
#define N 10 // array size N is known at compile time T static_array[N]; int n = 20; // array size n is calculated at runtime T* dynamic_array = new T[n]; std::vector<T> vector_array; // array size can be changed at runtime
Of course, you can still use the calloc() and malloc() functions and your
program will compile and run, but it’s not a good idea to mix C and C++
unless you have to because you’re relying on legacy C libraries. However you
allocate the array, you can access an element in it using an unsigned
integer index:
const T& element_of_static_array = static_array[index]; const T& element_of_dynamic_array = dynamic_array[index]; const T& element_of_vector_array = vector_array[index];
Let’s deal with dynamic arrays and vectors first, and return to the static array later in this chapter.
Dynamic Arrays
What would happen if we provide an index value that is
larger than or equal to the array size? In all three of the preceding
examples, the code will silently return garbage. (The exception to this
rule for Microsoft Visual Studio 2010 is discussed later.) The situation
is even worse if you decide to use the operator [] in the left-hand side
of an assignment:
some_array[index] = x;
Depending on your luck (or lack of thereof) you might overwrite some other unrelated variable, an element of another array, or even a program instruction, and in the latter ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access