Sub topic 10
Reference stability and invalidation
This chapter assumes you know the layout of arrays and linked lists from earlier chapters. It also assumes you are comfortable with references or pointers, and that you know what O(1) and O(n) mean.
What stability means
A reference is stable if it keeps pointing at the same element while the container changes. A reference is invalidated if the container's changes make it point at nothing, or at a different element.
This is a separate axis from speed. Two structures with the same Big-O costs can differ a lot in what your saved references still mean after an insert, delete or resize.
Linked lists: nodes never move
Each node of a linked list is allocated on its own. Inserting or removing other nodes only changes next (and prev) fields. The memory holding your node stays where it is, so a reference to it stays valid.
class Node:
def __init__(self, value, next=None):
self.value = value
self.next = next
def insert_after(node, value):
node.next = Node(value, node.next)
head = Node("a", Node("b", Node("c")))
saved = head.next # reference to the node holding "b"
insert_after(head, "x") # list is now a, x, b, c
print(saved.value) # b: the node is unchangedThe only way to invalidate saved is to remove that node itself. Even then, the node object still exists while you hold it. It is just no longer part of the list, and its next field may point into the list or at a node that was also removed. Treat a reference to a removed node as stale and drop it.
Arrays: positions shift
An array element has no identity beyond its position. If you remember "the element at index 1", any insert or delete before that index changes which element that is.
items = ["a", "b", "c"]
pos = items.index("b") # 1
items.insert(0, "x") # items is now x, a, b, c
print(items[pos]) # a: index 1 now holds a different elementNothing crashed. The index is still in range, but it now names the wrong element. This silent kind of bug is the usual failure in Python.
Dynamic arrays: growth can move everything
When a dynamic array runs out of capacity, it allocates a larger buffer and copies the elements across. Anything that pointed into the old buffer now points at memory that is no longer the array's storage.
You can watch this happen with the dynamic array from the growth chapter. Its internal buffer is replaced when it fills.
class DynamicArray:
def __init__(self):
self._capacity = 1
self._size = 0
self._items = [None] * self._capacity
def append(self, value):
if self._size == self._capacity:
self._resize(2 * self._capacity)
self._items[self._size] = value
self._size += 1
def _resize(self, new_capacity):
new_items = [None] * new_capacity
for i in range(self._size):
new_items[i] = self._items[i]
self._items = new_items
self._capacity = new_capacity
arr = DynamicArray()
arr.append(1)
buffer_before = arr._items
arr.append(2) # full at capacity 1, so this resizes
print(buffer_before is arr._items) # False: the storage movedIn Python this is harmless to your program's memory safety, because the old list stays alive as long as you hold it. It is just a stale copy. In languages with raw pointers, the story is worse.
What happens in other languages
In C++, std::vector::push_back can reallocate. When it does, all pointers, references and iterators into the vector are invalidated, and using them is undefined behavior. By contrast, std::list keeps references and iterators to other elements valid when you insert or erase. Only the erased element's own iterator is invalidated.
Python's built-in list holds references to objects. A reference to the object itself survives a resize, because the object is not copied. The slot that held it moves, and the index you remembered may not mean what it did.
Mutating a container while iterating over it is a related trap. Removing items from a Python list inside a for loop over that list skips elements, because the loop's hidden index no longer matches.
Common ways to cope
| Situation | Approach |
|---|---|
| You need long-lived handles to elements | Use a linked list, or store objects in the array and keep references to the objects. |
| You need array speed but also stable identity | Give each element a stable ID and keep a map from ID to current index. |
| You delete during iteration | Build a new list, or iterate over a copy. |
| You only append and never insert or delete in the middle | Indexes stay valid, but still do not keep raw pointers across an append in languages that expose them. |
Appending to the end of an array never changes the index of existing elements. Only the underlying buffer may move. This is why index-based handles survive appends but not front or middle inserts.
Why this matters for choosing
If your design hands out references to elements, for example a cache that stores node pointers in a hash map, stability can decide the choice before speed does. This is the reason LRU caches pair a hash map with a doubly linked list. The map stores node references, and those references have to stay valid while nodes are moved and removed.
Exercise
A program stores the index of a user's record in a Python list so it can look the record up later. Another part of the program sometimes removes records from the front of the list. What goes wrong, and name two ways to fix it?
Show answer
After a removal at the front, every later record shifts down one position, so the saved index points at the wrong record (or is out of range). Fixes: store a reference to the record object instead of its index, or give each record a stable ID and look it up through a dictionary. A linked list whose node references you keep would also work.
Exercise
Why does appending to a dynamic array never change the index of existing elements, yet it can still invalidate a raw pointer to an element in C++?
Show answer
Appending adds at the end, so earlier elements keep their positions. If the append triggers a resize, though, the elements are copied to a new buffer at a different memory address, so a pointer into the old buffer is invalidated even though the index is unchanged.