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.
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 |
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) |