Course contentsShow
← Computer Science
Lesson 2104 of 2,87247. Memory Management in LanguagesFree lesson

Reference Counting Fundamentals

Understanding how reference counting tracks object lifetimes by maintaining a count of active references to each object.

Reference Counting Fundamentals

What you'll learn: How reference counting tracks when objects can be safely deallocated by maintaining a running count of how many references point to each object.

The Core Idea

Reference counting is a memory management technique where every object carries a counter that tracks how many active references (pointers or variables) currently point to it. When you create a new reference to an object, the counter increments. When a reference goes out of scope or is reassigned, the counter decrements. When the count reaches zero, no code can possibly access that object anymore, so the memory can be immediately freed.

How It Works

Think of it like a shared apartment: each person who has a key (reference) to the apartment adds to a counter at the door. When someone moves out and returns their key, the counter decreases. When the last person moves out (count reaches zero), the landlord knows the apartment is empty and can prepare it for new tenants (deallocate memory).

Unlike garbage collection techniques you've seen (mark-and-sweep, copying collection), reference counting doesn't need to pause your program to trace through memory. Deallocation happens immediately when the last reference disappears.

Example Without Code

Imagine an object A starts with refcount = 0. A variable x points to it: refcount = 1. Then variable y also points to A: refcount = 2. When x goes out of scope: refcount = 1. Finally, when y is reassigned to something else: refcount = 0, and A is immediately freed.

Limitations

Reference counting has a critical weakness: circular references. If object A references object B, and B references A, both have refcount ≥ 1 forever, even when no external code can reach them. This creates memory leaks.

Key Takeaway: Reference counting tracks object lifetimes by incrementing a counter for each new reference and decrementing when references disappear, freeing memory immediately when the count hits zero—but struggles with circular references.