Two objects reference each other and nothing else references them. What frees them in CPython?
Options
- Reference counting frees them immediately, since both are unused
- The cyclic garbage collector, from the
gcmodule, finds and frees them (Correct option) - Nothing frees them, so they stay in memory until the program exits
- The operating system reclaims them when the thread finishes
Answer
The cyclic garbage collector (gc module)
Why
CPython mainly frees memory with reference counting: every object counts how many references point to it, and when the count reaches 0 it is deleted at once.
In a cycle (A points to B and B points to A) the counts never reach 0, even if the rest of the program no longer uses them.
A second mechanism, the cyclic garbage collector, runs from time to time, finds these unreachable groups and frees them.
Remember
Reference counting frees most objects; the gc cleans up cycles.