Definition
Use-after-free is the error of using a block of memory through a pointer after the block has been freed. Freeing a block hands it back to the allocator, the library code that manages the memory a program requests while it runs. A pointer is a value that holds a memory address, and it still holds the old address after the block is freed. A read or write through it therefore reaches whatever the allocator has placed at that address since, often a new and unrelated object.
The idea
The error typically involves two holders of one pointer. One holder frees the block. The other holder does not know, and goes on using its copy. Take a program that keeps one record for each network session and frees the record when the session closes. A timer that was set earlier still holds a pointer to the record, and when it fires it writes the current time into the record. By then the allocator may have given the same memory to a different session, and the write lands in the record of a stranger.
A reassigned telephone number is a fair picture. A friend gives up a number, and the telephone company later gives it to someone else. A caller who dials the saved number reaches the new subscriber and may say things that were meant for the friend. The picture stops being accurate in one respect: the new subscriber would say “wrong number”. Memory does not answer back.
How it works
The error unfolds in five steps.
The program allocates block A. Two parts of the program each keep a pointer to A.
The first part frees A. The allocator records the block as available and may store its own records inside it.
The second part still holds its pointer. A pointer in this state is called a dangling pointer §4.1.
A later allocation, B, may receive the same block.
The second part uses its pointer.
The effect of step 5 depends on the kind of use. A read returns old data, records of the allocator or the content of B. A write damages the records of the allocator or silently changes B. If the block holds the address of a function that the program then calls, whoever controls the content of B decides which code runs.
The same error appears when shared data is replaced while it is in use. Several threads, which are sequences of instructions that one program runs side by side, share a pointer named current. A reader thread loads current and then works with the object it points to. An updater thread builds a new object and stores its address in current. This step is called publication. A reader that loads current afterwards gets the new object, but a reader that loaded current shortly before publication is still working with the old object. Freeing the old object is called reclamation. If the updater reclaims at once, that reader commits a use-after-free.
Three families of techniques make reclamation wait until no reader is still using the old object.
A lock. A lock is an object that only one thread can hold at a time; any other thread that asks for it waits. A reader holds the lock from the moment it loads the pointer until its last use of the object, and the updater holds the same lock during publication and reclamation.
Reference counting §9.22. Each object carries a count of its users. A reader adds 1 before using the object and subtracts 1 afterwards, and the object is freed when the count reaches 0. Loading the pointer and adding 1 must happen under one protection, such as a lock, because otherwise the object could be freed between the two steps.
Deferred reclamation. The updater publishes at once and frees later. In read-copy update §9.20 (RCU), the updater waits for a grace period §9.21, a wait that ends only when every reader that was active at publication has finished. With hazard pointers, each reader announces the pointer it is using in a place that the updater checks before freeing.
Worked example
Object A occupies 16 bytes at the invented address 0x20002000, and current points to A.
Reader R loads
currentand gets0x20002000.Updater U stores the address of a new object B in
current.U frees A.
Another part of the program allocates 16 bytes and receives
0x20002000. It stores a password there.R reads the 4-byte field at bytes 4 to 7 of what it believes is A. It gets 4 bytes of the password.
Every reader that starts after step 2 gets B and is safe. The error needs R to load before step 2 and to read after step 3. The time between those two moments can be very short, so tests rarely hit it.
Here is the same sequence with reference counting. The count of A starts at 1, for the reference held by current.
R takes a reference to A, that is, adds 1 to the count, while holding a lock that also protects
current. Count: .U stores B in
currentand gives up the reference thatcurrentheld. Count: , so A is not freed.R reads its field from A and then gives up its reference. Count: . A is freed now, after its last use.
Stated precisely
Let be the event that frees block A. A use-after-free is any access to the memory of A, through a pointer that came from the allocation of A, whether directly, as a copy or by arithmetic, that happens after . A correct program makes every access to a block before the block is freed. In a program with several threads, that order must be guaranteed by a lock, a count or another mechanism that coordinates the threads. The usual timing of the program is not a guarantee.
When shared data is replaced, the old object A may be reclaimed only when two conditions hold.
Unpublished. No reader can newly obtain a pointer to A.
No longer in use. Every reader that obtained a pointer to A earlier has finished using it.
Publication of the new object establishes condition 1 only.
The C standard lists the use of a pointer to freed space among the undefined behaviors §4.12, which means that the standard places no requirement on what the program does.
Limits and common mistakes
A passing test proves nothing. A freed block usually keeps most of its old content until the allocator hands it out again. A read through a dangling pointer then often returns the expected value, and the error stays hidden until the timing changes.
A bounds check does not help. The access lies inside the bounds of the old block. The guarantee that every access lands inside its object is called spatial memory safety §2.28. The guarantee that the object still exists at the time of the access is called temporal memory safety §2.29, and it needs a different mechanism.
Making the exchange of the pointer safe is not enough. A lock that readers hold only while they load the pointer, or an atomic operation §9.8 that makes the exchange indivisible, protects the exchange. Neither says anything about readers that loaded the old pointer earlier and are still using the object.
Neither waiting nor keeping is a cure. A fixed delay before freeing only makes the error rarer, because a reader can be paused for longer. Never freeing turns the error into a memory leak §4.8, memory that is never given back.
Test tools see only what the tests run. AddressSanitizer §10.22, a tool that adds checks to a compiled program, reports a use-after-free only when one happens during a test.
Questions answered
Can an old reader overlap reclamation after an update?
Yes, unless the design explicitly prevents it. An update that stores a new pointer only redirects readers that fetch the pointer afterwards. A reader that fetched the old pointer shortly before the update is an old reader: it is still working with the old object. Reclamation means freeing the old object. If reclamation happens while an old reader is still at work, the reader reads or writes freed memory, which is a use-after-free.
Reclamation is safe only when no reader can newly obtain the old object and every reader that already obtained it has finished. Storing the new pointer establishes the first fact only, and a design must show how it knows the second. The usual answers are a lock that readers hold for the whole of their use, a count of users kept with the object, which is reference counting, or reclamation that is deferred until all readers that were active at the update have finished, as in read-copy update (RCU). A fixed delay does not show it, and neither does an indivisible exchange of the pointer.
Related entries: Object lifetime (§4.1), Reference counting (§9.22), Memory leak (§4.8), Double free (§4.7), Read-copy update (RCU) (§9.20), Grace period (§9.21), Temporal memory safety (§2.29). Further reading: [23, 25, 78].