Section 9.22

Reference counting

Definition

Reference counting is a way to decide when a shared object may be freed. The object carries a count of the references to it that are currently held, where a reference is a pointer together with the duty to release it later. Taking a reference adds one to the count; releasing it subtracts one. Whoever brings the count to zero frees the object, so no single owner has to know when the others are done. C++ std::shared_ptr works this way.

The idea

A network driver receives a packet into a buffer and hands the buffer to three consumers: a logger, a parser and a statistics module. Each consumer runs in its own thread (one of several instruction sequences sharing one memory) and finishes at a different time. Someone must free the buffer. If the driver frees it after handing it over, a consumer that is still working reads freed memory, a use-after-free §4.6. If nobody frees it, the memory is lost, a memory leak §4.8. No single party knows which consumer will finish last.

Counting the users solves this. Think of a meeting room where everyone who enters adds a mark on a board and everyone who leaves wipes one off; whoever wipes off the last mark switches off the light. Nobody needs to know who else is inside. The picture stops at the door. A person can only walk into a room that still exists. In a program, adding one to the count of an object that has already been freed is not entering a dark room: it is writing into memory that may now belong to something else. Taking the first reference safely is the hard part of reference counting.

How it works

The scheme has three operations.

  1. Create. A new object starts with count 1, the creator’s reference.

  2. Acquire, often called get: add 1 to the count. Only a thread that is sure the object is still alive may do this: a thread that already holds a reference, or one that found the object under a protection that keeps the object’s memory allocated.

  3. Release, often called put: subtract 1 from the count. If the result is 0, the releasing thread frees the object. After releasing, the thread must not use the object again.

Passing a reference to another thread hands over the duty to release it, and the count does not change. A counted reference is also called a strong reference.

When several threads share the object, the count must change by atomic operations §9.8: read-modify-write steps that no other thread can interleave with. Release must subtract and test in one step. The C function atomic_fetch_sub(&count, 1) returns the value the count had before the subtraction, and the one thread whose call returns 1 is the thread that brought the count to zero. A separate subtraction followed by a separate test would let two threads both see zero and both free the object, a double free §4.7. The usual memory ordering has three parts. The increment uses relaxed ordering, which makes the step atomic but orders no other memory access, because a thread that increments already holds a live reference. Each decrement uses release ordering. The thread that saw zero executes an acquire fence just before it frees the object, which keeps the freeing after every load the thread made before the fence. With that ordering, every write that any holder made to the object happens before the free (see the acquire-release ordering §9.11 entry).

A thread that finds an object through a shared table, without holding a reference yet, needs protection between finding the object and incrementing its count. Two patterns are standard.

A weak reference names an object without keeping it alive. To use the object, the holder turns the weak reference into a strong one with increment-if-not-zero; C++ std::weak_ptr::lock() does this on a separate control block that outlives the object. Holding a strong reference for exactly the length of one operation, so that the object cannot be freed until the operation ends, is often called pinning the object.

Worked example

The driver from the opening creates the buffer: count 1. Before handing the buffer over, the driver acquires one reference for each consumer: 1+1+1+1=41 + 1 + 1 + 1 = 4. The driver releases its own reference: 4−1=34 - 1 = 3. The statistics module finishes: 3−1=23 - 1 = 2. The parser finishes: 2−1=12 - 1 = 1. The logger finishes last: 1−1=01 - 1 = 0, so the logger’s release frees the buffer. Had the logger finished first, the parser or the statistics module would have freed the buffer instead; nobody had to know the order in advance.

Now suppose the decrement is not atomic: each thread loads the count, subtracts 1 and stores the result. With the count at 2, the parser and the logger release at the same moment. Both load 2, both compute 2−1=12 - 1 = 1, and both store 1. Two references were released, so the count should be 0, but it is 1. Nobody will ever free the buffer: a memory leak caused by a lost update.

Next, an unprotected acquire. A table holds the only reference to object O at address 0x2000, so O’s count is 1.

  1. Thread R loads the address 0x2000 from the table, holding no lock and no reference.

  2. The table’s owner removes O from the table and releases the table’s reference: 1−1=01 - 1 = 0, so the owner frees O.

  3. The memory allocator places a new object N at 0x2000. The word in which O kept its count now holds part of N, say the value 5.

  4. Thread R increments what it believes is O’s count. The word becomes 5+1=65 + 1 = 6.

Thread R has corrupted N and believes it holds a reference to an object that no longer exists. An increment-if-not-zero would not have saved R: it would have seen 5, which is not 0, and succeeded.

Finally, a cycle. Object A holds a reference to object B, and B holds a reference back to A. One outside variable holds a reference to A. A’s count is 1+1=21 + 1 = 2 (the variable and B), and B’s count is 1 (from A). The variable is dropped: A’s count becomes 2−1=12 - 1 = 1. Neither count is 0, so neither object is ever freed, although no part of the program can reach either one. If B’s reference back to A is weak instead, A’s count is 1 from the start. Dropping the variable brings it to 1−1=01 - 1 = 0, A is freed and releases its reference to B, and B’s count goes to 1−1=01 - 1 = 0, so B is freed too.

Stated precisely

Let c(o)c(o) be the stored count of object oo, and let h(o)h(o) be the number of strong references to oo currently held. Count a reference as held from the atomic increment that creates it, or from the creation of oo for the first reference, until the atomic decrement that ends it. With this convention the invariant c(o)=h(o)c(o) = h(o) holds at every moment.

Safety. The object oo is freed by the thread whose decrement takes c(o)c(o) from 1 to 0. At that moment h(o)=0h(o) = 0, so no thread holds a reference, and no access to oo follows the free. This depends on five assumptions.

  1. Every access to oo, including an increment of its count, is made by a thread that holds a reference to oo or holds a protection that keeps the memory of oo allocated, such as the table’s lock or an RCU read-side critical section.

  2. No increment starts from 0, because a count of 0 means that destruction has begun.

  3. Each reference is released exactly once.

  4. The increment and the decrement-and-test are each one atomic operation, and the decrement uses release ordering, followed in the freeing thread by acquire ordering.

  5. The count never overflows: with a ww-bit unsigned count, at most 2w−12^{w} - 1 references are held at once.

Liveness. The object is eventually freed if every reference is eventually released. A cycle of strong references breaks this: each object in the cycle holds a reference to the next, so no count in the cycle reaches 0, even when nothing outside the cycle refers to it.

Limits and common mistakes

Reference counting cannot free a cycle of objects that refer to each other, as the worked example shows. Remedies are weak references for one direction, code that breaks the cycle explicitly, or an additional collector. CPython, the standard Python §12.23 interpreter §2.13, counts references and also runs a separate collector that finds unreachable cycles.

A count of fixed width can overflow. A 32-bit count returns to 0 after 232=4,294,967,2962^{32} = 4{,}294{,}967{,}296 increments. If a bug skips a release and an attacker can trigger that bug about 2322^{32} times, the count passes through zero, and a later release frees an object that a legitimate holder still uses, a use-after-free. The Linux type refcount_t saturates instead: once the count reaches a very large value it stops changing, so the object is never freed, which turns the bug into a memory leak instead of memory corruption.

One release too many frees the object while another holder still uses it, which leads to a use-after-free or a double free. One release too few keeps the object forever, a memory leak.

A reference keeps an object alive; it does not control who may change the object. Two holders that write the same field at the same time still cause a data race §9.3, and a reader can still see a mix of old and new field values. Changes need a lock, or the object must never change after it is shared (see the immutable publication §9.24 entry).

Every acquire and every release writes to the count. When many processors share one object, they all write one memory location, and the hardware must move that location between the processors’ caches on every write. RCU readers avoid this cost because they write nothing shared. A common design uses RCU for short reads and takes a strong reference only when a reference must outlive a read-side critical section.

The object is freed by whichever thread drops the last reference, at that moment. That thread may be an interrupt handler §6.12 or a time-critical thread, which then has to run the object’s cleanup code. The cleanup can take long, because releasing one object releases the objects it refers to, and so on. Systems that care hand the actual freeing to a separate worker thread.

Reference counting is not tracing garbage collection: it never examines which objects the program can still reach. It relies entirely on every holder releasing correctly.

Questions answered

Can a reader safely acquire a reference from an already unprotected pointer?

No: a reader cannot safely acquire a reference from a pointer it read without protection, because that pointer does not keep the object alive. By the time the reader increments the object’s reference count, the last holder may have released the object, and its memory may have been freed or given to a different object. The increment is then itself a use-after-free: a write into memory that the reader has no right to touch. Making the increment atomic does not help, because atomicity §8.3 concerns the update of the counter, not whether the counter still exists. An increment-if-not-zero operation does not help on its own either, because a different object now occupying that memory may hold a nonzero value where the count used to be.

The reader can acquire a reference safely in two ways. It can start from a reference it already holds. Or it can find the object under a protection that keeps the memory allocated until the increment has happened: the lock that the owner also takes before removing and releasing the object, or a read-copy update read-side critical section, the marked stretch of reader code during which read-copy update delays every free. In the second case the reader uses increment-if-not-zero, which refuses an object whose count has already reached zero and which is therefore being destroyed.

Related entries: Ownership (§4.2), Double free (§4.7), Read-copy update (RCU) (§9.20), ABA problem (§9.25), Use-after-free (§4.6), Memory leak (§4.8).