Memory Leak Hunting with tracemalloc
Memory leaks occur when stale references prevent garbage collection. Standard library `tracemalloc` hooks into Python's internal memory allocators, attributing heap blocks to the exact source code line that allocated them 🧠.
import tracemalloc
tracemalloc.start()
snap1 = tracemalloc.take_snapshot()
# Allocate data:
cache = [f"node_{i}" for i in range(5000)]
snap2 = tracemalloc.take_snapshot()
tracemalloc.stop()
# Compute allocation delta:
diffs = snap2.compare_to(snap1, "lineno")
print(f"Top delta: {diffs[0]} 🧠")
# 117. Memory Leak Hunting with tracemalloc Memory leaks occur when stale references prevent garbage collection. Standard library `tracemalloc` hooks into Python's internal memory allocators, attributing heap blocks to the exact source code line that allocated them 🧠. ```python import tracemalloc tracemalloc.start() snap1 = tracemalloc.take_snapshot() # Allocate data: cache = [f"node_{i}" for i in range(5000)] snap2 = tracemalloc.take_snapshot() tracemalloc.stop() # Compute allocation delta: diffs = snap2.compare_to(snap1, "lineno") print(f"Top delta: {diffs[0]} 🧠") ``` Setting `PYTHONTRACEMALLOC=10` in your environment enables multi-frame stack traces, allowing you to trace leaks across complex caller hierarchies directly to the culprit function 🚀! --- ### Question How does `snapshot2.compare_to(snapshot1, 'lineno')` pinpoint memory leaks? 🧠- [ ] a. It displays net byte differences and object counts between two snapshots, grouped by file and line number 🧠- [ ] b. It automatically purges memory blocks exceeding 1 megabyte - [ ] c. It converts Python dictionaries into immutable tuple structures - [ ] d. It dumps the process memory space to an external core file --- ### Challenge Start `tracemalloc`. Snapshot `s1`, allocate `[i for i in range(1000)]`, snapshot `s2`, stop tracemalloc. Compare with `s2.compare_to(s1, 'lineno')`. Print `diff[0].size_diff > 0`. 🎯 <details> <summary>Solution</summary> ```python import tracemalloc tracemalloc.start() s1 = tracemalloc.take_snapshot() data = [i for i in range(1000)] s2 = tracemalloc.take_snapshot() tracemalloc.stop() diff = s2.compare_to(s1, 'lineno') print(diff[0].size_diff > 0) ``` </details>