Roadmap › How Computers Work — CPU, Memory, OS, Processes and Threads › Module: Memory
Lessons in this course (11)
6. How memory is managed: manual, reference counting and garbage collection
Intermediate★ Must knowLesson 6 of 11
| Approach | How | Used by | Risks |
|---|---|---|---|
| Manual | malloc/free, new/delete | C, C++ | Leaks, use-after-free, double free |
| Reference counting | Each object counts references; freed at 0 | Swift, Python (plus cycle collector), COM, C++ shared_ptr | Cycles leak without extra work |
| Tracing garbage collection | Periodically find reachable objects from roots; free the rest | .NET, Java, JavaScript, Go | Pauses, extra memory |
| Ownership/borrowing | Compiler enforces single owner | Rust | Learning curve |
Tracing GC in short (what .NET does):
- Roots — stack references, static fields, CPU registers, GC handles.
- Mark — follow references from roots; everything reached is alive.
- Sweep/compact — free unreachable objects; move live ones together to remove gaps (fragmentation) and update references.
- 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.