Skip to content

Garbage Collection & Memory Profiling ​

This page covers garbage collection (GC), which prevents leaks, along with its limits, and the profiling tools that help you find leaks.

Garbage Collection ​

Analogy: Automatic Cleaner vs Cleaning by Hand ​

How each language manages memory:

C/C++ (manual)              Python/Java (automatic GC)
The developer cleans up     A cleaner (GC) cleans up on its own

malloc() → allocate         new Object() → allocate
...use...                   ...use...
free()   → release ✋       // released automatically 🤖
          ↑
     forget it and it leaks!

When Leaks Happen Even With GC ​

python
# A pattern that can leak even in Python!
cache = []  # global list

def problematic_function():
    data = [0] * (25 * 1024 * 1024)  # 25MB
    cache.append(data)  # added to a global
    # Even with GC, it cannot be freed because cache still references it!
    # → if a reference remains, GC cannot collect it either

GC's limit: if a reference remains, it cannot be collected → this is why this document recommended "improving garbage collection"

Memory Profiling Tools ​

Tools for Finding Leaks ​

C/C++ family:
┌─────────────┬──────────────────────────────────┐
│  Valgrind   │ Detects memory access errors, leaks │
│  AddressSan │ Detects memory errors via compile-time instrumentation │
└─────────────┴──────────────────────────────────┘

Python family:
┌─────────────┬──────────────────────────────────┐
│  tracemalloc│ Tracks memory allocations (standard library) │
│  memory_prof│ Measures memory usage line by line │
│  objgraph   │ Visualizes object reference graphs │
└─────────────┴──────────────────────────────────┘

# Python example
import tracemalloc
tracemalloc.start()

# ... run the suspicious code ...

snapshot = tracemalloc.take_snapshot()
for stat in snapshot.statistics('lineno')[:5]:
    print(stat)  # prints which line allocated how much

Summary ​

ItemDetails
C/C++The developer frees memory with free(); forget it and it leaks
Python/JavaGC frees memory automatically, but cannot collect it while a reference remains
C/C++ toolsValgrind, AddressSan
Python toolstracemalloc, memory_prof, objgraph

Source: Codyssey-B1/B4-2