5.10.7. Using Reference Counts

For some kinds of data structures, where each cell only belongs to one data structure, it is usually clear when you should delete memory. But if you employ memory sharing, where a given cell might belong to two or more data structures, knowing when to delete a cell can be much more difficult.

A standard way to deal with memory sharing is to use reference counts. In each cell, store a count of the number of pointers that the program owns that point to that cell. Each time you create a new pointer to a cell, add 1 to the cell's reference count. Each time you destroy a pointer to a cell, subtract 1 from the cell's reference count and check whether the reference count has become 0. If it has become 0, you know that you can delete that cell.