Sub topic 10
Resizing: allocate, copy, replace
This chapter assumes you know what size and capacity mean in a dynamic array, and that you can read basic Big-O notation. Here we focus on what happens at the moment an append finds the block full.
Why a full block cannot just grow
An array occupies one contiguous block of memory. The memory right after that block may already belong to something else, so the array cannot simply extend itself in place. The dynamic array solves this with three steps.
- Allocate a new, larger block.
- Copy every existing element into the new block.
- Replace the old block with the new one, and update the capacity.
The old block is then released, either by the garbage collector or by an explicit free, depending on the language.
The code
This is the minimal implementation. The resize logic lives in _resize.
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:
self._resize(2 * self._capacity)
self._data[self._size] = value
self._size += 1
def _resize(self, new_capacity):
new_data = [None] * new_capacity
for i in range(self._size):
new_data[i] = self._data[i]
self._data = new_data
self._capacity = new_capacityappend checks for a full block before it writes. _resize allocates new_data, copies the first size elements, then rebinds self._data and updates self._capacity. Because the swap happens last, the array stays valid if anything fails earlier.
Tracing a sequence of appends
Start with capacity 1. Each row shows the state after the append finishes.
| Append | Resize? | Elements copied | Size | Capacity |
|---|---|---|---|---|
| 1st | no | 0 | 1 | 1 |
| 2nd | yes | 1 | 2 | 2 |
| 3rd | yes | 2 | 3 | 4 |
| 4th | no | 0 | 4 | 4 |
| 5th | yes | 4 | 5 | 8 |
Most appends cost one write. A resize costs a copy of every element, which is O(n) for that single call. Resizes get rarer as the array grows, which is the basis for the amortized analysis in a later chapter.
Common errors
- Copying up to capacity instead of size. The slots past
sizehold placeholders, so copying them wastes work and can hide bugs. - Updating capacity but not the data reference. The array then claims room it does not have, and a later write raises an
IndexErroror corrupts memory. - Resizing after the write. The write fails or overwrites memory before the block has room.
- Keeping old references to internal storage. In languages with raw pointers or iterators, a resize invalidates them. C++
std::vectoriterators and pointers into the buffer become invalid after a reallocation. - Growing by a constant amount. Adding a fixed number of slots per resize makes many appends copy many elements. Geometric growth avoids this, as the next chapters show.
Exercise
A DynamicArray starts with capacity 1 and doubles on each resize. You append 9 items. How many resizes happen, and what is the final capacity?
Show answer
Resizes happen when appending the 2nd, 3rd, 5th and 9th items, so 4 resizes. Capacity goes 1, 2, 4, 8, 16, and the final capacity is 16.