Array bounds checking verifies that an index lies inside the valid range before reading or writing an array element. It prevents invalid memory access and makes failures explicit.
You use it whenever array access may receive an index from input, another computation, or an unsafe source.
Problem
Given an array of length and an index , determine whether:
If the condition holds, the access is valid. Otherwise, the access must fail safely.
Algorithm
Check the index before reading:
get(A, i):
if i < 0 or i >= length(A):
error "index out of bounds"
return A[i]Check the index before writing:
set(A, i, x):
if i < 0 or i >= length(A):
error "index out of bounds"
A[i] = xExample
Let
Then:
| index | condition | result |
|---|---|---|
| 2 | valid | |
| 5 | invalid | |
| -1 | invalid |
Reading index returns:
Reading index fails because the last valid index is .
Correctness
The valid indices of an array of length are exactly through . The condition accepts every valid index and rejects every invalid index. Therefore, any access that passes the check refers to an existing element, and any access that fails the check is prevented.
Complexity
| operation | time |
|---|---|
| bounds check | |
| checked get | |
| checked set |
Space usage:
When to Use
Bounds checking is appropriate when:
- indices come from user input
- indices come from arithmetic
- correctness and safety matter
- invalid access should produce a clear error
It is less suitable only in carefully audited low-level code where bounds are already proven and performance requires removing redundant checks.
Implementation
def get(a, i):
if i < 0 or i >= len(a):
raise IndexError("index out of bounds")
return a[i]
def set_value(a, i, x):
if i < 0 or i >= len(a):
raise IndexError("index out of bounds")
a[i] = xfunc Get[T any](a []T, i int) (T, bool) {
var zero T
if i < 0 || i >= len(a) {
return zero, false
}
return a[i], true
}
func Set[T any](a []T, i int, x T) bool {
if i < 0 || i >= len(a) {
return false
}
a[i] = x
return true
}