Code RoomUse-after-free in lock-free pop
HardPrep Room Coding #1862

Use-after-free in lock-free pop

Code reviewConcurrencySenior–Staff~40 min

Review this C++ lock-free Treiber stack pop.

A reviewer says this lock-free stack has a classic bug. Which one, and how does it manifest?

What a strong answer looks like

Separate real bugs from style. Rank issues by severity, point at the root cause rather than the symptom, and suggest a concrete fix, specific and kind.

0:00 of about 40 min
Mark a line and say what kind of problem it is.0 findings
1template <class T>
2struct Node { T val; Node* next; };
3 
4std::atomic<Node<int>*> head;
5 
6int pop() {
7 Node<int>* old = head.load(std::memory_order_acquire);
8 while (old &&
9 !head.compare_exchange_weak(old, old->next, // (1)
10 std::memory_order_acq_rel)) {
11 }
12 int v = old->val;
13 delete old; // (2) free immediately
14 return v;
15}
Which questions mattered is sealed until you submit. Telling you now would just be handing over the edge cases.