Memory Leak - Reference Counting and Cyclic References

Reference Counting and Cyclic References

More modern garbage collection schemes are often based on a notion of reachability - if you don't have a usable reference to the memory in question, it can be collected. Other garbage collection schemes can be based on reference counting, where an object is responsible for keeping track of how many references are pointing to it. If the number goes down to zero, the object is expected to release itself and allow its memory to be reclaimed. The flaw with this model is that it doesn't cope with cyclic references, and this is why nowadays most programmers are prepared to accept the burden of the more costly mark and sweep type of systems.

The following Visual Basic code illustrates the canonical reference-counting memory leak:

Dim A, B Set A = CreateObject("Some.Thing") Set B = CreateObject("Some.Thing") ' At this point, the two objects each have one reference, Set A.member = B Set B.member = A ' Now they each have two references. Set A = Nothing ' You could still get out of it... Set B = Nothing ' And now you've got a memory leak! End

In practice, this trivial example would be spotted straight away and fixed. In most real examples, the cycle of references spans more than two objects, and is more difficult to detect.

A well-known example of this kind of leak came to prominence with the rise of AJAX programming techniques in web browsers in the lapsed listener problem. Javascript code which associated a DOM element with an event handler and failed to remove the reference before exiting, would leak memory (AJAX web pages keep a given DOM alive for a lot longer than traditional web pages, so this leak was much more apparent).

Read more about this topic:  Memory Leak

Famous quotes containing the words reference and/or counting:

    In sum, all actions and habits are to be esteemed good or evil by their causes and usefulness in reference to the commonwealth, and not by their mediocrity, nor by their being commended. For several men praise several customs, and, contrarily, what one calls vice, another calls virtue, as their present affections lead them.
    Thomas Hobbes (1579–1688)

    If you’re counting my eyebrows, I can help you. There are two.
    Billy Wilder (b. 1906)