![]() |
|
P is for Practical | |
PerlMonks |
Circular references and Garbage collection.by DigitalKitty (Parson) |
on Aug 02, 2002 at 23:19 UTC ( #187246=perlquestion: print w/replies, xml ) | Need Help?? |
DigitalKitty has asked for the wisdom of the Perl Monks concerning the following question:
Hi all.
A former college professor of mine and I were discussing memory leaks and garbage collection in various scripting languages the other day, and he asked me how this issue was handled in perl ( he bought 'Learning Perl - 3rd edition' last week ). After explaining what I knew about references ( I'm still learning ), he asked me if I could research the topic so we could discuss it in more depth. So far, I have learned that perl handles this topic through a mechanism called reference counting. It seems each block of memory has an internal reference 'count' that stores the number of references which contain an address. If / When this number becomes zero, the memory that occupied that space is released ( freed ).
When $num is created, the reference count becomes 1. Then the reference count is incremented to 2 when $ref is assigned a reference to $num. When we reach the end of the inner block, $num goes out of scope and we can no longer reference it through $num. This has the effect of decrementing the reference count by 1. At the end of the outer block, $ref goes out of scope thereby dropping the reference count to zero. This will free any memory previously occupied. The problem occurs when one reference refers to another.
The reference cannot drop to zero and the memory it is occupying will never be freed ( the dreaded memory leak ). This can bring a machine to it's knees if left 'unattended'. Does anyone know of an efficient way to break circular references? Aside from assigning a value to the scalar $ref ( i.e. $ref = 15 ), I don't see a solution. Thanks in advance, -Katie.
Back to
Seekers of Perl Wisdom
|
|