Lessons in this course (11)

6. How memory is managed: manual, reference counting and garbage collection

Intermediate★ Must knowLesson 6 of 11
ApproachHowUsed byRisks
Manualmalloc/free, new/deleteC, C++Leaks, use-after-free, double free
Reference countingEach object counts references; freed at 0Swift, Python (plus cycle collector), COM, C++ shared_ptrCycles leak without extra work
Tracing garbage collectionPeriodically find reachable objects from roots; free the rest.NET, Java, JavaScript, GoPauses, extra memory
Ownership/borrowingCompiler enforces single ownerRustLearning curve

Tracing GC in short (what .NET does):

  1. Roots — stack references, static fields, CPU registers, GC handles.
  2. Mark — follow references from roots; everything reached is alive.
  3. Sweep/compact — free unreachable objects; move live ones together to remove gaps (fragmentation) and update references.
  4. Generations — new objects die young, so the GC checks young objects often (cheap) and old ones rarely.

The full .NET details (generations 0/1/2, Large Object Heap, workstation vs server GC, IDisposable, finalizers) are in the .NET Internals course.