develooper Front page | perl.perl5.porters | Postings from January 2012

[perl #109270] leak on accessing anon sub inside another one

Thread Previous | Thread Next
From:
Father Chrysostomos via RT
Date:
January 29, 2012 12:35
Subject:
[perl #109270] leak on accessing anon sub inside another one
Message ID:
rt-3.6.HEAD-14510-1327869347-1327.109270-15-0@perl.org
On Sun Jan 29 09:45:24 2012, jkeenan wrote:
> On Sun Jan 29 03:41:06 2012, LeonT wrote:
> > 
> > This is called a circular reference, and this kind of leaking is a
> > well known consequence of reference counting. If you want this not to
> > happen, try weakening one of the references.
> > 
> 
> Do the attached programs correctly document how to do this?

Not quite.  This program:

#!/usr/local/bin/perl
use strict;
use warnings;
use Scalar::Util qw( weaken );

sub leak {
    my ($foo, $bar);
    $foo = sub {  &$bar   };
    weaken($foo);
    $bar = sub {  "$foo"  };
    return;
}

sub psprint { print `ps -p$$ -ocommand,vsize` }

psprint;
leak() for (1..20000);
psprint;
__END__

causes $foo to be freed before $bar is ever called.  So it will
stringify undef.

What one has to do is create *two* scalars referencing the same thing. 
The one of them has to be weakened.  The closure must close over the
weak one:

sub leak {
    my ($foo, $foo_life_raft, $bar);
    $foo = $foo_life_raft = sub {  &$bar   };
    weaken($foo);
    $bar = sub {  "$foo"  };
    return;
}

I usually like to call the variable $life_raft or similar in my own
code, because it keeps the referent ‘afloat’ till the end of the
enclosing scope.

That example will work if $foo is the closure that will be returned or
assigned to something.  If $bar is to be returned, then $bar has to be
weakened (with a $bar_life_raft to keep it alive till the end of sub leak).

> 
> Results on Darwin/PPC; similar on Linux/i386:
> 
> $ perl 109270.pl 
> COMMAND               VSZ
> perl 109270.pl      28656
> COMMAND               VSZ
> perl 109270.pl      38180
> 
> $ perl 109270_weaken.pl 
> COMMAND               VSZ
> perl 109270_weak    28712
> COMMAND               VSZ
> perl 109270_weak    28712
> 
> If so, is the ticket closable?

Yes, in that it is behaving as documented.

-- 

Father Chrysostomos


---
via perlbug:  queue: perl5 status: open
https://rt.perl.org:443/rt3/Ticket/Display.html?id=109270

Thread Previous | Thread Next


nntp.perl.org: Perl Programming lists via nntp and http.
Comments to Ask Bjørn Hansen at ask@perl.org | Group listing | About