ABA
Same value, different world
The popper reads top = X and next = Y, then stalls. Another thread pops X, pops Y, frees Y, and pushes X back (X.next = Z). The popper resumes and runs CAS(top, X, Y), which sets top to Y only if top is still X. What happens?
Compare-and-swap checks one thing: is the word in memory still the value I read? It cannot see history. A lock-free stack pops by reading top (node X) and X.next (node Y), then CASing top from X to Y. If another thread pops X, pops Y, frees Y and pushes X back in the gap, top is X again but X.next is Z. The CAS sees X, succeeds, and installs Y, a freed node, as the top. The address came back; the world it described did not.
// pop(), lock-free, pointer-only CAS:
node* old = top; // X
node* next = old->next; // Y
// ... preempted. Another thread pops X, pops Y, frees Y,
// pushes X back. top == X again, but X->next == Z.
if (CAS(&top, old, next)) // compares the pointer only: succeeds
return old; // top is now Y, which is freed. Z is lost.// Tagged pointer: the CAS compares (pointer, version) as one word.
struct { node* p; uint64_t tag; } top;
for (;;) {
auto old = top; // (X, 0)
node* next = old.p->next;
if (CAS(&top, old, {next, old.tag + 1})) // (X, 3) != (X, 0): fails
return old.p; // retry re-reads next = Z
}
// Memory reclamation still needs hazard pointers, epochs or RCU. Watch the STACK panel: top → X → Y → Z → ∅, and the X.next row. In ABA, X.next changes from Y to Z while top is X both times the popper looks, and the invariant breaks the moment the CAS succeeds. In FIX: TAGGED POINTER the same interleaving makes the CAS fail on tag 0 ≠ 3, and the retry reads Z.
The popper reads top and top.next, then CASes. The mutator pops twice, frees the last node it popped and pushes the first one back. Interleave them so the CAS succeeds and leaves the stack corrupt.
GOAL: the CAS succeeds and top points at a freed node or a node is lost
Rewrite pop so a concurrent pop-pop-free-push between your reads and your CAS cannot corrupt the stack. The grader lets that sequence land once, between any two of your stack calls.
Lock-free stacks, queues and free-lists in allocators, kernels and high-frequency trading code. Any optimistic update keyed on a recycled id: a slot index, a reused connection number, a counter that wraps. Symptom: rare corruption or use-after-free far from the cause.
“Why can a CAS succeed when it should not?” Walk the stack example with the next pointer, say what the tag does and why it lives in the same word as the pointer (double-width CAS, or the unused upper bits of a 64-bit pointer; the 3 or 4 low alignment bits wrap far too soon), then say that tags do not solve reclamation and name hazard pointers or epochs. Bonus: explain why a GC makes the stack code safe as written.