Section 14.5

Array

Definition

An array is a data structure that stores a sequence of elements of one type in one contiguous block of memory and identifies each element by an integer index, counted from 0. Because the elements are equal in size and adjacent, the address of element ii is the start address plus ii times the element size, so any element is reached in constant time. A fixed-size array has a capacity set at creation; a dynamic array also records a logical length, its number of valid elements, and can grow.

The idea

A program reserves room for 16 sensor readings and has recorded 3 so far. Memory for all 16 exists, but only the first 3 slots hold readings; the other 13 hold whatever bytes were there before, perhaps zeros, perhaps data from an earlier use of that memory. A loop that runs up to 16 reports 13 meaningless values and may expose old data. So an array that is not always full needs two numbers: how many slots exist, the capacity, and how many hold valid elements, the logical length.

Arrays are used for their address arithmetic: because all elements have the same size and sit side by side, finding element ii is a calculation, not a search. A row of numbered lockers is a fair picture: locker 7 is found by counting along the row, without opening lockers 0 to 6. The picture stops at the unused lockers. An unused array slot is not empty; it holds some pattern of bits, and nothing in the memory marks it as unused. Only the length says which slots are valid.

How it works

An array is described by these quantities:

A fixed-size array, such as int a[16] in C, has no length of its own; a program that fills it only partly must keep the length in a separate variable. A dynamic array, such as std::vector in C++, ArrayList in Java or the list type of Python §12.23, keeps the base address, length and capacity together and grows when full.

The operations follow from that layout.

  1. Read or write element ii: check 0≤i<n0 \le i < n, against the length, not the capacity; then use the address b+i⋅sb + i \cdot s.

  2. Append: if n<capn < \mathrm{cap}, write the new element into slot nn first and only then increase nn by 1, so that the length never counts an unwritten slot. If n=capn = \mathrm{cap}, grow first.

  3. Grow: reserve a new block, usually twice as large; copy the nn valid elements into it; release the old block; record the new base address and capacity. With growth by a constant factor, any mm appends cost at most a constant times mm, although one append may copy every element; the amortized analysis §14.4 entry proves this.

  4. Insert or delete at index ii: shift every later element one slot right or left, which moves n−in - i or n−i−1n - i - 1 elements.

  5. Remove the last element: decrease nn by 1. The removed element’s bytes stay in memory until overwritten.

Two further consequences of the layout matter in practice. A pass from index 0 upward reads memory in address order, which processor caches (small fast memories that hold recently used data and the data next to it) serve well; a linked list §14.6, whose elements are scattered across memory, is usually much slower to scan. And a two-dimensional array of RR rows with KK elements each, stored row after row as C stores it, places element (r,k)(r, k) at address b+(r⋅K+k)⋅sb + (r \cdot K + k) \cdot s.

Worked example

An array starts at the illustrative address 1000, holds 4-byte integers, and has capacity 16 and length 3.

Appending writes the new element into slot 3, at address 1000+3×4=10121000 + 3 \times 4 = 1012, and then sets the length to 4. Suppose instead that the array is full, with length 16 and capacity 16. The next append reserves a block of 32 slots, 32×4=12832 \times 4 = 128 bytes, which the memory allocator places at address 2000, say. The append copies the 16 elements, 64 bytes, to addresses 2000 to 2063, writes the new element at 2000+16×4=20642000 + 16 \times 4 = 2064, sets the length to 17 and the capacity to 32, and releases the old block. Element 2 now lives at 2000+2×4=20082000 + 2 \times 4 = 2008. A pointer saved earlier to element 2 still holds the address 1008, which now lies in released memory: it is a dangling pointer §4.1, and using it is a use-after-free §4.6.

Stated precisely

Let bb be the base address, ss the element size in bytes, cap\mathrm{cap} the capacity, nn the logical length and ii an index. The array keeps the invariant 0≤n≤cap0 \le n \le \mathrm{cap}. The reserved block is the half-open byte range [b,b+cap⋅s)[b,\ b + \mathrm{cap} \cdot s), meaning the addresses from bb up to but not including b+cap⋅sb + \mathrm{cap} \cdot s. Element ii occupies the range [b+i⋅s,b+(i+1)⋅s)[b + i \cdot s,\ b + (i + 1) \cdot s). An access to element ii is valid when 0≤i<n0 \le i < n and the block is still reserved. An append fits without growing when n<capn < \mathrm{cap}.

On a machine, the check must come before any arithmetic that could overflow: compare the index with the length first, i<ni < n, and only then compute i⋅si \cdot s. Hold ii in an unsigned type, or also check i≥0i \ge 0, so that a negative index cannot pass. Computing b+i⋅sb + i \cdot s first and comparing the address with the end of the block fails when i⋅si \cdot s exceeds the largest value of its type and wraps around to a small number. A check in the safe order is an overflow-safe range check §4.17. In C, a pointer may point one element past the end of an array, where it may be compared but not used to read or write; forming any pointer further out is undefined behavior §4.12.

Limits and common mistakes

An index below the capacity is not necessarily a valid index. Slots nn to cap−1\mathrm{cap} - 1 lie inside reserved memory but hold no valid element, only leftover data, possibly from an earlier user of that memory, or bytes never written. In C such a slot holds an indeterminate value, and the language gives no guarantee about what a read of it returns.

Reducing the length erases nothing. An array that held a secret, such as a key, must be cleared explicitly, with a clearing function that the compiler cannot remove as a useless write.

A C array does not carry its length. Passed to a function, it becomes a pointer to its first element, so the function must receive the length as a separate argument; sizeof applied to such a parameter gives the size of a pointer, not of the array.

Off-by-one errors are the classic array bug. The valid indices are 0 to n−1n - 1, so a loop that continues while i≤ni \le n reads one element too many.

Growing invalidates every pointer into the old block, as the worked example shows. Code that keeps a position across an append must keep the index instead, or reserve enough capacity in advance that no growth happens.

Constant-time indexing does not make every operation cheap. Inserting or deleting in the middle moves up to nn elements, and an append that grows the array copies all of them.

When several threads (flows of execution that share memory) use one array, a reader may see the new length before the new element is written. The writer must publish the length so that a reader who sees the new length also sees the element: a mutex §9.5 (a lock that one thread at a time can hold) around both does this, and so does an atomic store of the length with release ordering, read by an atomic load with acquire ordering. Without either, the program has a data race §9.3.

Questions answered

What is the difference between allocated capacity and current logical length?

Allocated capacity is the number of element slots for which memory has been reserved; current logical length is the number of those slots, counted from index 0, that currently hold valid elements. Always 0≤length≤capacity0 \le \text{length} \le \text{capacity}. The length decides which indices may be read or written: index ii is valid only when 0≤i<length0 \le i < \text{length}. The capacity decides whether an append fits without growing: it fits when the length is less than the capacity; otherwise the array must reserve a larger block and copy its elements into it.

An index between the length and the capacity lies inside reserved memory, so using it does not leave the block, but the slot holds no valid element, only leftover or never-written bytes. Checking reads against the capacity instead of the length is therefore a bug that can return stale data, including secrets left by earlier use. An array with capacity 16 and length 3, for example, has 16 reserved slots, but only indices 0, 1 and 2 hold elements.

Related entries: Overflow-safe range check (§4.17), Amortized analysis (§14.4), Peak versus retained memory (§11.37), Object lifetime (§4.1), Out-of-bounds read (§4.5), Pointer arithmetic (§4.25), Deamortization: spreading array migration while preserving lookup meaning (§14.40).