calin has asked for the wisdom of the Perl Monks concerning the following question:

Quick question: does keeping a reference to an array element or hash value prevent the freeing of the container object when all the "direct" references to it go away? My impression (90% sure) is that the answer is no - elements do not impose "upward reference-counting" to their container (it would be blatantly anti-DWIMish and a severe source of memory leaks) - but I want to be 100% sure.

# create a reference to an anon array my $aref = [1..100]; # take a reference to one of its elements my $elem_ref = \$aref->[50]; # drop the array reference undef $aref; # is the anon array still gobbling up memory in a zombie state?

Replies are listed 'Best First'.
Re: Query on refcounting with container objects
by dragonchild (Archbishop) on Jul 29, 2004 at 19:21 UTC
    Yes and no. Perl doesn't release the memory back to the OS. However, the memory isn't accessible, which means it's available for reallocation before Perl asks the OS for more memory.

    ------
    We are the carpenters and bricklayers of the Information Age.

    Then there are Damian modules.... *sigh* ... that's not about being less-lazy -- that's about being on some really good drugs -- you know, there is no spoon. - flyingmoose

    I shouldn't have to say this, but any code, unless otherwise stated, is untested

      But it will (should, if it doesn't, it's a bug) destroy the array and all elements in it and reuse their memory in perl except for the one element that still has a refcount > 0.

      So, a standard perl container (hash or array) will have a reference to its elements, but not the other way around. This is also true for regular references; they only point 1 way and only up the refcount for the variable that they point to.

      One thing is to say that the process of the Perl interpreter got an amount of memory from the OS, and other thing is to say that Perl internally uses this memory with a SV, where a SV in Perl can be a data type (SCALAR, ARRAY, HASH, CODE, etc...).

      So, when a reference to a SV goes out, yes, this will be undefined/destroied, and the memory (inside the process) used to represent this SV will be used in the future for new SVs.

      Now about keep some back reference of who hold a SV, like in an ARRAY or HASH, I say that not! The SV doesn't know if it exists inside another ARRAY or HASH value, it's just a SV.

      Graciliano M. P.
      "Creativity is the expression of the liberty".

Re: Query on refcounting with container objects
by fergal (Chaplain) on Jul 29, 2004 at 19:59 UTC
    The following confirms that you're impression is correct
    package a; sub DESTROY{print "hash destroyed\n"}; $b=bless {a=> 1}, "a"; $c=\$b->{a}; $b=undef; print "still holding a reference to $$c\n";