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:
- allocates a larger buffer somewhere else,
- copies (or moves) every element into it,
- 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
istays 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 aSpan<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 (whatforeachuses) records the list's version. After anyAdd,Removeor similar change, the nextMoveNextthrowsInvalidOperationException, 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 acrosspush_backin C++. - Modifying a collection inside a
foreachover 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++) andTrimExcess(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.