Typically, garbage collection strategies would start from the pointers on the stack and traverses the heap to determine which objects are live. The unreachable objects can be garbage collected.

Diagramming

Draw the Stack and the Heap at the point of execution like normal program understanding questions.

Reference Counting Scenario

In this situation here, Person1 and Person2 each have one reference even though they are unreachable, therefore memory is leaked.

Clean Up Options

  1. Don’t lol
    • TUI applications usually just reclaim memory when they terminate, but most interactive programs cannot do this.
  2. Programming languages like C++ let you manage your own memory. This is why you want to implement destructors
  3. Automatic
    • The programmer can just rely on automatic garbage collection to reclaim space by objects that are no longer needed. Most modern programming languages implement this. Rust is interesting here.

Related

Choosing a strategy is about Engineering Design and judgement.