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:

    Indiana was really, I suppose, a Democratic State. It has always been put down in the book as a state that might be carried by a close and careful and perfect organization and a great deal of—[from audience: “soap”Ma reference to purchased votes, the word being followed by laughter].
    I see reporters here, and therefore I will simply say that everybody showed a great deal of interest in the occasion, and distributed tracts and political documents all through the country.
    Chester A. Arthur (1829–1886)

    What culture lacks is the taste for anonymous, innumerable germination. Culture is smitten with counting and measuring; it feels out of place and uncomfortable with the innumerable; its efforts tend, on the contrary, to limit the numbers in all domains; it tries to count on its fingers.
    Jean Dubuffet (1901–1985)