liveBook · Manning

Garbage collection

As explained in Refactoring to Rust

Garbage collection is automatic reclamation of memory that is no longer reachable by a program.

Garbage collection automatically reclaims heap memory when no program variables refer to it. Background runtime code periodically checks those references, so developers do not explicitly deallocate each value. section 2.2

Automatic memory management trades manual cleanup for simpler allocation:

  • Manual memory management requires developers to allocate the right amount and deallocate it at the right time. section 2.2
  • Garbage collection removes the explicit deallocation step and reduces errors such as use-after-free. section 2.2
  • Rust avoids a run-time garbage collector while still providing tools for controlling memory allocations when performance requires it. section 1.2

Explicit cleanup versus automatic cleanup

A K welcome program calls free(name) after using the input. Garbage-collected languages perform the corresponding reclamation automatically when the value is no longer referenced, while Rust handles ownership and cleanup without a run-time collector. section 2.2 section 1.2

Listing 2.6 The welcome program written with K
def welcome(name):
  print('Welcome ' + name)

name = input('Please enter your name: ')
welcome(name)
free(name)

Compare the explicit free(name) call with automatic reclamation and see why manual cleanup places responsibility on the developer. section 2.2

How Refactoring to Rust covers it

How deep it goes
Defines heap reclamation through reference checks and contrasts its safety and allocation trade-offs with manual management.
Examples
Uses a K welcome program with explicit free(name) calls to illustrate the burden of manual deallocation.
What you can do after
Evaluate whether automatic reclamation fits performance-sensitive software and explain Rust's alternative.
How it connects
Connects garbage collection with manual memory management, heap memory, memory allocation, and use-after-free errors.

Also explained in

Compare how 9 books explain garbage collection →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Refactoring to Rust. The section links point to the parts of the book it draws on.