Skip to content

Array Bounds Checking

Validate array indices before access to prevent invalid reads and writes.

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 AA of length nn and an index ii, determine whether:

0i<n 0 \le i < n

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] = x

Example

Let

A=[8,3,5,1,9] A = [8, 3, 5, 1, 9]

Then:

indexconditionresult
202<50 \le 2 < 5valid
505<50 \le 5 < 5invalid
-101<50 \le -1 < 5invalid

Reading index 22 returns:

5 5

Reading index 55 fails because the last valid index is 44.

Correctness

The valid indices of an array of length nn are exactly 00 through n1n - 1. The condition 0i<n0 \le i < n 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

operationtime
bounds checkO(1)O(1)
checked getO(1)O(1)
checked setO(1)O(1)

Space usage:

O(1) O(1)

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] = x
func 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
}