M02 · Memory Model

Reallocation and Invalidated References: When a Buffer Moves

A dynamic array that runs out of room allocates a bigger buffer, copies its elements across and lets the old buffer go. Anything that pointed into the old buffer is now wrong. C++ calls using it undefined behaviour; C#, Java and Python each protect you in a different way. This lesson walks through all four.

~30 minBeginnerC# · Python · Java · C++
Curriculum: M02 Memory Model · 5 of 5 lessons available

You will be able to

  • Explain why a dynamic array cannot simply grow in place and must sometimes move.
  • State which C++ operations invalidate pointers, references and iterators into a std::vector.
  • Describe how C# spans and enumerators, Java iterators and Python memoryviews behave when the collection changes.
  • Apply the safe patterns: reserve capacity, re-acquire views, or modify through the iterator.

Helpful before this lesson

  • M01 Algorithmic Thinking — Turn a vague task into precise inputs, outputs and constraints, then argue that a solution is correct.

Guidance only. Those modules are planned; the essentials are recapped here.

Visual walkthrough

The interactive visualizer needs JavaScript. The explanation and all four implementations below work without it.

Mental model

A dynamic array (List<T>, ArrayList, Python list, std::vector) keeps its elements in one buffer with some spare capacity. When an append finds the buffer full, it:

  1. allocates a larger buffer somewhere else,
  2. copies (or moves) every element into it,
  3. releases the old buffer.

It cannot just extend the old buffer, because the memory right after it may belong to something else. So the elements change address. Any pointer, reference, iterator or view that pointed into the old buffer now points at memory the array no longer uses. The lab shows both buffers while the copy runs, and the old pointer left behind.

The lab's growth policy doubles the capacity. Real libraries differ and may change between versions: libstdc++ and .NET's List<T> double, Microsoft's STL and OpenJDK's ArrayList grow by about half, and CPython's list over-allocates by roughly an eighth. See Dynamic arrays for why any constant factor keeps appends amortized O(1).

C++: invalid means undefined behaviour

std::vector promises that push_back reallocates only when the new size exceeds capacity(). When it does, every pointer, reference and iterator into the vector is invalidated. When it does not, they all stay valid except end(). insert and erase invalidate everything at or after the position they touch, and everything if insert reallocates.

Using an invalid pointer is undefined behaviour. It might read the old value, read garbage, crash, or corrupt unrelated data, and it can behave differently in a debug and a release build. The program in the listings never dereferences the stale pointer; it checks capacity() and then takes v.data() again. Tools help catch mistakes: AddressSanitizer reports use-after-free, and debug modes of the standard libraries (such as _GLIBCXX_DEBUG or MSVC's iterator debugging) check iterators.

Safe patterns:

  • call reserve(n) before taking pointers if you know how many elements will be added;
  • keep indices instead of pointers: index i stays meaningful across a reallocation;
  • re-acquire pointers and iterators after any operation that may reallocate.

C#: memory-safe, but stale

C# code cannot hold a raw pointer into a List<T> without unsafe code, and the garbage collector never frees an array that something still refers to. Two cases are worth knowing:

  • CollectionsMarshal.AsSpan(list) gives a Span<T> over the list's current backing array. After the list grows, the span still views the old array: reads return old values and writes no longer reach the list. Nothing crashes; the data is just silently stale. The documentation says not to add or remove items while the span is in use.
  • A List<T> enumerator (what foreach uses) records the list's version. After any Add, Remove or similar change, the next MoveNext throws InvalidOperationException, whether or not the array grew.

Java: fail-fast iterators

Java code never holds a pointer into an ArrayList's backing array, so nothing can dangle, and references to the elements stay valid across growth: the array of references moved, the objects did not need to. What breaks is iteration. ArrayList counts structural modifications in modCount; an iterator remembers the value it started with, and its next() throws ConcurrentModificationException if they differ. The Javadoc calls this behaviour best effort: use it to find bugs, not for correctness.

To change a list while iterating, use the iterator's own remove (or ListIterator.add), or removeIf, or collect the changes and apply them afterwards.

Python: a view stops the resize

A Python list gives you no pointer into its storage. Iterating while appending raises no error: the iterator simply works by index, so appending inside a for loop over the same list can loop forever, and removing skips elements. Dicts and sets do check: changing their size during iteration raises RuntimeError.

Buffers behave differently again. A memoryview exports the memory of a bytearray (or an array.array) directly. While any export exists, the object refuses to resize and raises BufferError, so the view can never dangle. Release the view (view.release(), or a with block) before resizing.

Costs

A reallocation copies all n elements: O(n) for that append, amortized O(1) over a sequence of appends with geometric growth. Reserving capacity in advance turns a series of reallocations into one allocation.

Common mistakes

  • Keeping &v[0] or an iterator across push_back in C++.
  • Modifying a collection inside a foreach over it in C# or Java.
  • Holding a Span<T> over a list across calls that may add to it.
  • Assuming "it worked in my test" means a C++ dangling pointer is fine.

Edge cases

  • Enough capacity: in C++ no reallocation happens and pointers stay valid; the C# span still sees the live array; the Java iterator still throws (any structural change counts); Python still refuses.
  • Removing elements never reallocates a std::vector, but it does invalidate iterators at and after the removal point.
  • shrink_to_fit (C++) and TrimExcess (C#) may reallocate too.

Worked practice

1. A std::vector<int> has size 3 and capacity 4. You take int* p = &v[0] and call push_back twice. Is p valid afterwards?

Answer

Not necessarily. The first push_back fits (size 4 ≤ capacity 4), but the second needs size 5 > 4, so the vector reallocates and p is invalid.

2. In Java, you call list.add(x) inside a for-each loop over list with plenty of capacity. What happens?

Answer

The next call to the hidden iterator's next() throws ConcurrentModificationException. Growth is irrelevant; any structural change counts.

Summary

  • Growing a dynamic array moves its elements to a new buffer.
  • C++: reallocation invalidates all pointers, references and iterators; using them is undefined behaviour.
  • C#: spans go stale and enumerators throw; Java: iterators throw; Python: memoryviews block resizing.
  • Keep indices, reserve capacity, or re-acquire views after changes.

Full implementation

The teaching growth model in four languages against one shared fixture, plus the real behaviour it explains: a stale Span and an InvalidOperationException in C#, BufferError under a memoryview in Python, ConcurrentModificationException in Java, and in C++ a capacity check (never a dereference) after reallocation and pointer stability without one.

using System.Runtime.InteropServices;
 
namespace Bekadan.Dsa.Examples.Memory;
 
/// <summary>
/// What happens to a view into a List&lt;T&gt; when the list outgrows its array.
/// C# stays memory-safe: the old array lives on while something refers to it, but a
/// view taken before the growth is stale, and enumerators refuse to continue.
/// </summary>
public static class Reallocation
{
    /// <summary>The Memory Lab's teaching growth policy: double when full. List&lt;T&gt; also doubles, but that is an implementation detail.</summary>
    public static (int Reallocations, int Copies, int Capacity) SimulateGrowth(int capacity, int count, int appends)
    {
        int reallocations = 0, copies = 0;
        for (int i = 0; i < appends; i++)
        {
            if (count == capacity)
            {
                int newCapacity = Math.Max(1, capacity * 2);
                copies += count;               // every element moves to the new array
                capacity = newCapacity;        // the old array is dropped; the GC reclaims it once unreachable
                reallocations++;
            }
            count++;
        }
        return (reallocations, copies, capacity);
    }
 
    /// <summary>A span taken before the list grows keeps viewing the old array.</summary>
    public static void StaleSpan()
    {
        var list = new List<int>(capacity: 2) { 1, 2 };
        Span<int> span = CollectionsMarshal.AsSpan(list);
        list.Add(3);                           // full: the list allocates a bigger array and copies
        span[0] = 99;                          // lands in the old array
        Check(list[0] == 1, "the list does not see a write through a stale span");
        span = CollectionsMarshal.AsSpan(list);
        span[0] = 99;
        Check(list[0] == 99, "a fresh span views the current array");
    }
 
    /// <summary>Enumerators check a version number: any Add makes MoveNext throw, growth or not.</summary>
    public static void FailFastEnumerator()
    {
        var list = new List<int>(capacity: 8) { 1, 2 };
        using var enumerator = list.GetEnumerator();
        enumerator.MoveNext();
        list.Add(3);                           // no growth needed, still a modification
        bool threw = false;
        try
        {
            enumerator.MoveNext();
        }
        catch (InvalidOperationException)
        {
            threw = true;
        }
        Check(threw, "MoveNext after Add throws InvalidOperationException");
    }
 
    private static void Check(bool condition, string claim)
    {
        if (!condition) throw new InvalidOperationException($"Claim failed: {claim}");
    }
}

Tested on .NET 10 (SDK 10.0.403), C# 14 · examples/csharp/Bekadan.Dsa.Examples/Memory/Reallocation.cs

"""Growth and views: Python never lets a buffer move under a live memoryview."""
 
 
def _check(condition: bool, claim: str) -> None:
    if not condition:
        raise AssertionError(f"Claim failed: {claim}")
 
 
def simulate_growth(capacity: int, count: int, appends: int) -> tuple[int, int, int]:
    """The Memory Lab's teaching growth policy: double when full. (CPython's list grows by about 1/8 instead.)"""
    reallocations = copies = 0
    for _ in range(appends):
        if count == capacity:
            new_capacity = max(1, capacity * 2)
            copies += count  # every element moves to the new buffer
            capacity = new_capacity  # the old buffer is freed
            reallocations += 1
        count += 1
    return reallocations, copies, capacity
 
 
def buffer_refuses_to_move() -> None:
    buf = bytearray([1, 2])
    view = memoryview(buf)
    try:
        buf.append(3)  # resizing while the buffer is exported is refused
        refused = False
    except BufferError:
        refused = True
    _check(refused and len(buf) == 2, "a bytearray cannot resize while a memoryview exists")
    view.release()
    buf.append(3)
    _check(buf == bytearray([1, 2, 3]), "after release the bytearray grows normally")
 
 
def dict_resize_during_iteration_raises() -> bool:
    """A dict detects a size change during iteration. (A list does not: appending while iterating just keeps going.)"""
    d = {1: "a"}
    try:
        for key in d:
            d[key + 1] = "b"
    except RuntimeError:
        return True
    return False

Tested on CPython 3.14.0 · examples/python/dsa_examples/memory_reallocation.py

package dev.bekadan.dsa.memory;
 
import java.util.ArrayList;
import java.util.ConcurrentModificationException;
import java.util.Iterator;
import java.util.List;
 
/**
 * What happens to an iterator and to element references when an ArrayList grows.
 * Java code never holds a pointer into the backing array, so nothing can dangle;
 * iterators detect structural changes instead (fail-fast, best effort).
 */
public final class Reallocation {
    private Reallocation() {
    }
 
    /** The Memory Lab's teaching growth policy: double when full. ArrayList grows by about half instead. Returns {reallocations, copies, capacity}. */
    public static int[] simulateGrowth(int capacity, int count, int appends) {
        int reallocations = 0;
        int copies = 0;
        for (int i = 0; i < appends; i++) {
            if (count == capacity) {
                int newCapacity = Math.max(1, capacity * 2);
                copies += count;                    // every reference moves to the new array
                capacity = newCapacity;             // the old array becomes garbage
                reallocations++;
            }
            count++;
        }
        return new int[] {reallocations, copies, capacity};
    }
 
    public static void failFastIterator() {
        List<Integer> list = new ArrayList<>(List.of(5, 6));
        Iterator<Integer> it = list.iterator();
        list.add(7);                                // a structural modification: modCount changes
        boolean threw = false;
        try {
            it.next();
        } catch (ConcurrentModificationException expected) {
            threw = true;
        }
        check(threw, "next() after add throws ConcurrentModificationException");
        it = list.iterator();
        check(it.next() == 5, "a fresh iterator works");
    }
 
    /** References to elements survive growth: the array of references moved, the objects did not need to. */
    public static void elementReferencesSurvive() {
        List<StringBuilder> list = new ArrayList<>(1);
        StringBuilder first = new StringBuilder("a");
        list.add(first);
        for (int i = 0; i < 100; i++) {
            list.add(new StringBuilder());
        }
        first.append("b");
        check(list.get(0) == first && list.get(0).toString().equals("ab"), "a reference taken before growth still reaches the element");
    }
 
    private static void check(boolean condition, String claim) {
        if (!condition) {
            throw new AssertionError("Claim failed: " + claim);
        }
    }
}

Tested on Java 25 (Temurin 25.0.5); also compiles on Java 17 · examples/java/src/main/java/dev/bekadan/dsa/memory/Reallocation.java

#pragma once
 
#include <algorithm>
#include <cassert>
#include <vector>
 
namespace bekadan::dsa::memory {
 
struct Growth {
    int reallocations;
    int copies;
    int capacity;
};
 
// The Memory Lab's teaching growth policy: double when full. (libstdc++ also doubles;
// MSVC's STL grows by half. The standard only requires amortized constant push_back.)
inline Growth simulate_growth(int capacity, int count, int appends) {
    int reallocations = 0;
    int copies = 0;
    for (int i = 0; i < appends; ++i) {
        if (count == capacity) {
            const int new_capacity = std::max(1, capacity * 2);
            copies += count;                      // every element is moved to the new buffer
            capacity = new_capacity;              // the old buffer is freed
            ++reallocations;
        }
        ++count;
    }
    return {reallocations, copies, capacity};
}
 
// A pointer into a vector dies with the buffer it pointed into.
inline void reallocation_invalidates() {
    std::vector<int> v{10, 20, 30};
    int* p = &v[0];
    const auto old_capacity = v.capacity();
    while (v.size() <= old_capacity) v.push_back(40);  // eventually exceeds the capacity
    assert(v.capacity() > old_capacity);  // reallocated: p and every reference and iterator into v are invalid
    // *p here would be undefined behaviour, so p is not used again until it is refreshed
    p = v.data();
    assert(*p == 10);
}
 
// Without reallocation, push_back keeps pointers and references to elements valid.
inline void no_reallocation_keeps_pointers() {
    std::vector<int> v;
    v.reserve(8);
    v.push_back(1);
    const int* p = &v[0];
    v.push_back(2);  // size <= capacity: no reallocation; only end() is invalidated
    assert(p == &v[0] && *p == 1);
}
 
}  // namespace bekadan::dsa::memory

Tested on C++23, GCC 15.3 (libstdc++) · examples/cpp/include/bekadan/dsa/memory/reallocation.hpp

References