Memory management decides who allocates, tracks, and frees the bytes your program uses. C++ hands that job to you. Java, Python, and JavaScript hand it to a runtime. Each approach changes your performance profile, your bug surface, and the way you write code.
Quick Takeaways
- C++ uses deterministic, scope-based cleanup (RAII) with no garbage collector. You control lifetimes, and you own the bugs.
- Java uses a generational garbage collector on the JVM heap. Pause times are tunable, but memory leaks still happen through lingering references.
- Python (CPython) combines reference counting with a cyclic garbage collector. Most objects die the instant their count hits zero.
- JavaScript (V8) uses a generational mark-and-sweep collector. Closures, listeners, and detached DOM nodes cause most leaks.
| Feature | C++ | Java | Python (CPython) | JavaScript (V8) |
|---|---|---|---|---|
| Primary strategy | Manual + RAII | Tracing GC | Ref counting + cycle GC | Generational mark-and-sweep |
| Cleanup timing | Deterministic | Non-deterministic | Mostly deterministic | Non-deterministic |
| Pause risk | None from GC | Low to moderate | Low (cycle GC only) | Low to moderate |
| Memory overhead | Lowest | Moderate | Highest per object | Moderate |
| Leak risk | Dangling pointers, forgotten delete |
Retained references | Cycles with __del__, globals |
Closures, listeners, timers |
| Learning curve | Steep | Moderate | Gentle | Gentle |
Foundational Concepts: Stack vs. Heap
Every language in this guide uses two memory regions. The stack stores function frames and local variables. It allocates and frees in O(1) time because it only moves a pointer. The heap stores objects whose lifetime extends beyond a single function call. Allocation there is slower and needs bookkeeping.
Here is stack allocation in C++:
#include <iostream>
void stackDemo() {
int count = 42; // Lives on the stack
double ratio = 0.75; // Lives on the stack
std::cout << count << " " << ratio << "\n";
} // Both variables vanish here automatically
The output is 42 0.75. When stackDemo() returns, the stack pointer moves back and both variables disappear. No cleanup code is needed.
Here is heap allocation in C++:
#include <iostream>
void heapDemo() {
int* values = new int[1000]; // Heap allocation
values[0] = 7;
std::cout << values[0] << "\n";
delete[] values; // You must free it manually
}
The program prints 7. If you skip delete[], those 4,000 bytes leak until the process exits.
In Java, Python, and JavaScript, objects live on the heap and variables hold references. The runtime decides when an object is unreachable and reclaims it.
C++ Memory Management
C++ gives you direct control. It has no runtime collector, so memory behavior is predictable down to the instruction.
Manual Allocation with new and delete
Raw new and delete work, but they invite three classic bugs:
- Memory leak: you forget to call
delete. - Double free: you call
deletetwice on the same pointer. - Dangling pointer: you use a pointer after the memory is freed.
RAII and Smart Pointers
RAII (Resource Acquisition Is Initialization) ties a resource’s lifetime to an object’s scope. When the object is destroyed, its destructor releases the resource. Modern C++ expresses this through smart pointers in <memory>.
#include <iostream>
#include <memory>
#include <string>
struct Session {
std::string user;
explicit Session(std::string u) : user(std::move(u)) {
std::cout << "Opened: " << user << "\n";
}
~Session() { std::cout << "Closed: " << user << "\n"; }
};
int main() {
// Exclusive ownership. Zero overhead compared to a raw pointer.
auto a = std::make_unique<Session>("alice");
// Shared ownership. Uses an atomic reference count.
auto b = std::make_shared<Session>("bob");
auto c = b; // Count is now 2
std::cout << "bob refs: " << b.use_count() << "\n";
} // bob and alice destructors run automatically
The output shows Opened: alice, Opened: bob, bob refs: 2, then both Closed lines as the scope ends. No delete appears anywhere.
| Smart Pointer | Ownership | Overhead | Use Case |
|---|---|---|---|
| std::unique_ptr | Single owner | None | Default choice for heap objects |
| std::shared_ptr | Shared, ref-counted | Control block + atomic ops | Multiple owners, shared lifetime |
| std::weak_ptr | Non-owning observer | Control block access | Breaking cycles, caches |
Use std::weak_ptr to break cycles. Two shared_ptr objects pointing at each other never reach a count of zero.
Java Memory Management
The JVM manages a heap divided into generations. Most objects die young, so the collector optimizes for that pattern.
Heap Structure and Garbage Collection
- Young generation: new objects start here. Minor collections are frequent and fast.
- Old generation: objects that survive several young collections get promoted here. Major collections are rarer and costlier.
- Metaspace: class metadata lives outside the heap in native memory.
The default collector since Java 9 is G1, which splits the heap into regions and targets a pause-time goal. ZGC and Shenandoah aim for very short, mostly concurrent pauses on large heaps. Recent JDK releases include a generational mode for ZGC.
Leaks Still Happen in Java
A garbage collector frees unreachable objects. It cannot free objects you still reference by accident.
import java.util.HashMap;
import java.util.Map;
public class UserCache {
// Static field: lives as long as the class is loaded
private static final Map<Long, byte[]> CACHE = new HashMap<>();
public static void load(long userId) {
CACHE.put(userId, new byte[1_000_000]); // 1 MB per entry, never evicted
}
}
Every call to load() adds 1 MB that the collector can never reclaim. Calling it a million times ends in an OutOfMemoryError.
Use try-with-resources for non-memory resources such as files and sockets:
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class FileRead {
public static String firstLine(String path) throws IOException {
// The reader closes automatically, even if an exception is thrown
try (BufferedReader reader = new BufferedReader(new FileReader(path))) {
return reader.readLine();
}
}
}
The method returns the first line and always closes the file handle. Closing resources promptly matters because the garbage collector does not guarantee when, or whether, finalization runs.
Python Memory Management
CPython combines two systems. Reference counting frees most objects immediately. A cyclic garbage collector finds groups of objects that reference each other.
Reference Counting in Action
import sys
data = [1, 2, 3]
print(sys.getrefcount(data)) # 2: the variable + the call argument
alias = data
print(sys.getrefcount(data)) # 3
del alias
print(sys.getrefcount(data)) # 2
The first call prints 2 because passing data as an argument temporarily adds a reference. Binding alias raises the count to 3. Deleting alias drops it back. When the count reaches zero, CPython frees the object at once.
Reference Cycles and the gc Module
Reference counting fails on cycles. Two objects that point at each other never reach zero on their own.
import gc
import weakref
class Node:
def __init__(self, name):
self.name = name
self.peer = None
a = Node("a")
b = Node("b")
a.peer = b
b.peer = a # Cycle: counts never reach zero
probe = weakref.ref(a)
del a, b
print(probe() is None) # False: the cycle keeps the objects alive
gc.collect() # The cycle collector finds and frees them
print(probe() is None) # True
The first check prints False and the second prints True. CPython runs the cycle collector automatically in three generations, but gc.collect() forces it to run now. Use weakref to hold references that should not keep an object alive.
To cut per-instance memory, define __slots__ on classes with many small instances. It removes the per-instance __dict__:
class Point:
__slots__ = ("x", "y") # No __dict__, smaller instances
def __init__(self, x: float, y: float) -> None:
self.x = x
self.y = y
The trade-off is that you cannot add new attributes to instances at runtime.
JavaScript Memory Management
V8 powers Chrome and Node.js. It uses a generational design with two main spaces:
- Young generation (new space): a fast Scavenger collector copies live objects and discards the rest.
- Old generation: a mark-and-sweep collector with mark-compact passes handles long-lived objects. V8 runs much of this work incrementally and concurrently to reduce pauses.
An object is collectable when no path from a root (globals, the active call stack) reaches it.
Common Leak: Forgotten Listeners and Timers
function mountWidget() {
const bigBuffer = new Array(1_000_000).fill("x");
// The closure captures bigBuffer. The interval keeps the closure alive.
setInterval(() => {
console.log(bigBuffer.length);
}, 1000);
}
mountWidget(); // bigBuffer is never collected
The interval callback references bigBuffer through a closure, and the timer system references the callback. The buffer stays alive until you call clearInterval().
Weak References for Caches
const metadata = new WeakMap();
function track(element) {
// The entry disappears automatically once `element` is unreachable
metadata.set(element, { clicks: 0 });
}
let button = { id: "save" };
track(button);
button = null; // The WeakMap entry becomes eligible for collection
A WeakMap holds its keys weakly, so it never blocks collection of the key object. Use it instead of a plain Map when you attach data to objects you do not own.
Side-by-Side: Performance and Safety Trade-offs
| Criterion | C++ | Java | Python | JavaScript |
|---|---|---|---|---|
| Allocation speed | Fast (stack), moderate (heap) | Very fast (bump allocation) | Moderate | Fast |
| Latency predictability | Highest | Tunable by collector | Good, with cycle GC spikes | Good, with GC jitter |
| Memory safety | Developer-dependent | Strong | Strong | Strong |
| Manual control | Full | Limited (JVM flags) | Limited (gc, weakref) |
Minimal |
| Best fit | Games, embedded, systems | Enterprise services, big data | Scripting, ML, automation | Web UIs, Node.js services |
Best Practices: Bad Code vs. Good Code
C++: Raw Pointers vs. Smart Pointers
Bad code (anti-pattern):
Widget* build() {
Widget* w = new Widget();
if (!w->init()) {
return nullptr; // Leak: w is never deleted
}
return w; // Caller must remember to delete
}
Good code (refactored):
std::unique_ptr<Widget> build() {
auto w = std::make_unique<Widget>();
if (!w->init()) {
return nullptr; // w is destroyed automatically
}
return w; // Ownership transfers to the caller
}
The refactored version cannot leak on the early return. The return type documents ownership.
Python: Unbounded Cache vs. Bounded Cache
Bad code (anti-pattern):
_results = {}
def compute(key):
if key not in _results:
_results[key] = expensive(key) # Grows forever
return _results[key]
Good code (refactored):
from functools import lru_cache
@lru_cache(maxsize=1024) # Evicts least recently used entries
def compute(key):
return expensive(key)
lru_cache caps memory at 1,024 entries and evicts the oldest unused result.
JavaScript: Orphaned Listener vs. Cleanup
Bad code (anti-pattern):
function attach(el) {
window.addEventListener("resize", () => el.classList.toggle("wide"));
}
Good code (refactored):
function attach(el) {
const controller = new AbortController();
window.addEventListener(
"resize",
() => el.classList.toggle("wide"),
{ signal: controller.signal }
);
return () => controller.abort(); // Call this on unmount
}
The returned function removes the listener, so the element can be collected after teardown.
How to Find Memory Problems
| Language | Tool | What It Reveals |
|---|---|---|
| C++ | AddressSanitizer, Valgrind | Leaks, use-after-free, buffer overflows |
| Java | VisualVM, JFR, Eclipse MAT | Heap dumps, allocation hot spots, retained size |
| Python | tracemalloc, objgraph |
Allocation traces, growing object types |
| JavaScript | Chrome DevTools heap snapshots | Detached DOM nodes, retained closures |
Take two snapshots, run the suspect workflow, then compare. Objects that grow between snapshots are your leak candidates.
FAQ
Does Python have a garbage collector?
Yes. CPython frees most objects through reference counting the moment their count reaches zero. A separate cyclic garbage collector, exposed through the gc module, finds and frees groups of objects that reference each other.
Why doesn’t C++ have garbage collection?
C++ prioritizes deterministic performance and zero-overhead abstractions. RAII and smart pointers give automatic cleanup without a runtime collector, so destruction happens at a predictable point in the code.
Can Java have memory leaks if it has a garbage collector?
Yes. The collector only frees unreachable objects. Static collections, unclosed listeners, and long-lived caches keep references alive, so the objects stay in memory even though the program no longer needs them.
How does JavaScript garbage collection work?
V8 uses a generational mark-and-sweep collector. It starts from roots, marks every reachable object, and frees the rest. A fast Scavenger handles short-lived objects in the young generation, and a mark-compact pass handles the old generation.



