Memory Lab · simulation 4 of 5
Reallocation and invalidated references
A dynamic array outgrows its buffer and moves. See what happens to a pointer, span, iterator or memoryview that pointed into the old one.
The full explanation is in the lesson Reallocation and invalidated references.
What to watch for
- Growth allocates a second buffer, copies every element, then lets the first one go.
- C++: the pointer still holds the old address, and using it is undefined behaviour.
- C# keeps the old array alive under a stale span; Java’s iterator throws; Python refuses to resize at all.
In each language
- C#
- A Span from CollectionsMarshal.AsSpan goes stale; an enumerator throws InvalidOperationException.
- Python
- A bytearray with a live memoryview raises BufferError instead of resizing.
- Java
- Iterators are fail-fast (best effort): ConcurrentModificationException after any add.
- C++
- Reallocation invalidates every pointer, reference and iterator into the vector.
The programs
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<T> 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<T> 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