![]() |
![]() |
0 ≤ index ≤ size-1
, we generalize that any index value < 0 or ≥ size causes an out-of-bounds error. (No Diet Coke was spilled while photographing this illustration.)
The behavior of a program indexing an array out of bounds is unpredictable and erratic. Three conditions associated with the memory accessed by the out-of-bounds indexing account for most of the program's arbitrary behavior:
Remembering that C++ does not automatically test array indexes for out-of-bounds conditions is software developers' first step toward creating safe, secure, and robust code. Their next step is understanding when a program must test an index before using it and when a test is an unnecessary expense.
Door doors[3]; int door; cout << "Choose a door: "; cin >> door; if (door > 0 && door <= 3) ... doors[door - 1]...; else cerr << "Valid doors are 1, 2, or 3" << endl;
int scores[100]; int score; int count = 0; cout << "Enter a score (-1 to stop): "; cin >> score; while (score != -1 && count < 100) { scores[count++] = score; cin >> score; } |
int scores[100]; int count = 0; cout << "Enter a score (-1 to stop): "; do { cin >> scores[count++]; } while (scores[count - 1] != -1 && count < 100); count--; // discard the -1 |
for (. . . i . . .) for (. . . j . . .) . . . array[i - j] . . .
Although it is possible to include an if-statement inside a loop to detect this kind of error, it incurs the expense of a needless test. The example illustrates a programmer-created logical error, which, when identified and corrected, will not cause further problems. Rather than adding a test, rigorously validate the code, using the debugger to locate and identify any errors.
![]() |
int input(int* scores, int capacity) { int count = 0; while (count < capacity && ...) cin >> scores[count++]; return count; } |
void print(int* scores, int size) { for (int i = 0; i << size; i++) cout << scores[i] << endl; } |
const int size = 8; int capacity; int scores[size]; |
||
(a) | (b) | (c) |