Sub topic 4
Valid Indexes and Out-of-Range Errors
This chapter assumes you know basic programming (variables, loops, functions), introductory Big-O notation, and roughly what a memory address is. It covers which indexes an array accepts, what happens when you use one that is not valid, and how a dynamic array enforces the rule.
What counts as a valid index
An array of n elements uses zero-based indexes. The valid range is 0 through n - 1. Index 0 is the first element, and index n - 1 is the last.
The rule comes from the memory layout. An element's address is the start address plus index * element_size. Index 0 adds nothing, so it points at the first element. Index n would point at the first byte after the array, which is not part of it.
What happens when the index is wrong
Languages handle an invalid index in different ways.
| Language | Behavior on an invalid index |
|---|---|
| Python | Raises `IndexError` |
| Java | Throws `ArrayIndexOutOfBoundsException` (or `IndexOutOfBoundsException` for `ArrayList`) |
| C and C++ raw arrays | Undefined behavior: no check is made |
| C++ `vector::at` | Throws `std::out_of_range` |
| C++ `vector::operator[]` | Undefined behavior: no check is made |
An unchecked access reads or writes whatever memory lies at that address. It may return garbage, corrupt another variable, or crash. This is a well-known source of security bugs. A checked language turns the same mistake into an immediate, readable error.
Checking indexes in a dynamic array
A dynamic array has two numbers: size (elements in use) and capacity (slots allocated). The valid index range depends on size, not capacity. Slots between size and capacity exist in memory but hold no meaningful data.
The DynamicArray class from this tutorial checks against size on reads:
class DynamicArray:
def __init__(self):
self._capacity = 1
self._size = 0
self._data = [None] * self._capacity
def __len__(self):
return self._size
def __getitem__(self, index):
if not 0 <= index < self._size:
raise IndexError("index out of range")
return self._data[index]
def append(self, value):
if self._size == self._capacity:
new_data = [None] * (2 * self._capacity)
for i in range(self._size):
new_data[i] = self._data[i]
self._data = new_data
self._capacity *= 2
self._data[self._size] = value
self._size += 1
arr = DynamicArray()
arr.append("a")
arr.append("b")
arr.append("c")
print(arr[2])
try:
print(arr[3])
except IndexError as error:
print("caught:", error)After three appends, the capacity is 4 and the size is 3. The program prints c, then caught: index out of range. Index 3 is inside the allocated block, but the check rejects it because it is not below the size.
Different limits for different operations
The upper limit is not the same for every operation:
- Reading or overwriting an element:
0 <= index < size. - Inserting:
0 <= index <= size. Inserting atsizeis allowed because it means "add at the end". - Removing the last element: the array must not be empty.
Mixing up < and <= is the most common off-by-one error here.
Common errors
- Looping with
range(len(a) + 1), which reaches indexsize. - Checking against capacity instead of size, which exposes unused
Noneslots. - Using an index from a stale length after elements were removed.
- Assuming a negative index is an error in Python, or that it is safe in other languages.
Exercise
A dynamic array has size 5 and capacity 8. Which indexes can you read, and which index values are accepted by insert?
Show answer
You can read indexes 0 through 4, because reads need 0 <= index < size. Insert accepts 0 through 5, because inserting at index 5 appends at the end. Indexes 5 to 7 exist in memory but are not readable.