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:

    A sign, or representamen, is something which stands to somebody for something in some respect or capacity. It addresses somebody, that is, creates in the mind of that person an equivalent sign, or perhaps a more developed sign. That sign which it creates I call the interpretant of the first sign. The sign stands for something, its object. It stands for that object, not in all respects, but in reference to a sort of idea, which I have sometimes called the ground of the representamen.
    Charles Sanders Peirce (1839–1914)

    Is it not manifest that our academic institutions should have a wider scope; that they should not be timid and keep the ruts of the last generation, but that wise men thinking for themselves and heartily seeking the good of mankind, and counting the cost of innovation, should dare to arouse the young to a just and heroic life; that the moral nature should be addressed in the school-room, and children should be treated as the high-born candidates of truth and virtue?
    Ralph Waldo Emerson (1803–1882)