Master the fundamental concepts of garbage collection through this focused micro-challenge.
You have read the whole brief, and the concepts above stay free on every task. Writing and running the code needs a plan.
Three hints are available for this task, revealed one at a time inside the code workspace so you can struggle productively before seeing them.
Every task includes starter code, theory, and hidden tests so you can implement and verify locally in the browser.
How it worksStrong refs keep objects alive; weak refs observe without retaining. Java WeakReference and Swift weak let caches and parent pointers avoid cycles. When only weak refs remain, object is collectable.
Weak ref field does not increment refcount or mark bit. On collection, weak refs null out. Finalizers run once after weak resolution in some runtimes.
cLoading…
Production compilers embed this step inside a longer pipeline. GCC flows through cpp, cc1, assembly, and ld; Clang uses the driver, Sema, LLVM IR passes, and a target backend. LLVM bitcode, JVM bytecode, and WASM are other familiar IRs at the same layer. The exercise isolates one pass so you can test it alone before chaining it to the next stage.
You will implement weak references for breaking reference cycles. This exercise asks you to track weak slots separately from strong roots so objects are collected when only weakly reachable.
Add weak references to a reference-counted heap: the mechanism behind C++ std::weak_ptr, Rust Weak<T>, Swift weak and Python weakref. A weak reference lets you reach an object without keeping it alive: it doesn't count, and when the object is freed every weak reference to it is cleared to null. Use it to break the parent↔child cycle that plain reference counting leaks.
| Command | Meaning |
|---|---|
new NAME | create NAME with strong count 1: the program (main) holds one root reference |
release NAME | main drops one root reference: −1 strong |
strong A B | A gets a strong pointer to B: +1 strong on B |
drop A B | remove A's first strong pointer to B: −1 strong on B |
weak A B | A gets a weak pointer to B (no count change). A may be main |
deref A B | read A's weak pointer that was created to B |
upgrade A B | if that weak pointer is still set, add a strong pointer A → B |
main is not an object and is never freed. Names are unique.
When a strong count reaches 0:
free NAME (K weak refs cleared) and set every weak pointer to it to null. K counts only pointers not already cleared;cLoading…
Then at the end:
cLoading…
A tree where the child points back to its parent weakly:
Input:
cLoading…
Output:
cLoading…
Hidden tests cover the same parent↔child cycle made of two strong pointers (it leaks), upgrade succeeding and failing, weak pointers held by objects that are themselves freed, and weak pointers to an object that another object keeps alive.