develooper Front page | perl.perl5.porters | Postings from September 1999

Re: Memory leak with tie()

Thread Previous
From:
Ian Phillipps
Date:
September 26, 1999 03:45
Subject:
Re: Memory leak with tie()
Message ID:
19990926112037.A11493@homer.diplex.co.uk
On Sat, 25 Sep 1999 at 22:53:12 +0100, Paul Breslaw wrote:

> Could someone explain why the attached code leaks memory?  It's odd
> because if the infinite loop is  while (<>) { .. }  it leaks; but
> if it's  while (1) { .. }  it doesn't.

> package Leak;
> use FileHandle;

> sub new {
>     my $self = new FileHandle;
FileHandle is obsolescent; you probably want IO::File instead.

>     bless $self, "Leak";

Here, you're subverting the FileHandle object: you've taken away its
FileHandle-blessedness, and not done anything to compensate. In
particular, you have no @ISA. Note also that the second argument to
bless is redundant, and furthermore this is bad OO practice: Leak cannot
be subclassed the way you've written it.

Maybe you've not been banging your forehead with the textbook for long
enough :-)

>     my %retval;
>     tie %retval, "Leak", $self;
>     return bless \%retval, "Leak";

Hmm... and now you're making Leak be two different things: the
FileHandle-that-was and a reference to the tied hash. ???

> }

> sub DESTROY {
>     my $self = tied(%{$_[0]});
>     $self->DESTROY;

This doesn't do any good, since $self is now a 'Leak', not a
FileHandle. I've not worked out why it doesn't bitch and moan more.
Anyhow, it's not serving any useful purpose, and confuses the hell out
of me.

Remove the DESTROY completely and your leak disappears. The usual rule
is that you don't need a DESTROY, unless it's reclaiming some specific
resource like a lock - which this isn't. If you use the OO-versions of
the IO system, they will clean themselves up automatically - but you
must let them run a DESTROY if they want to. 

In older versions of Perl, your subversive re-blessing of the FileHandle
object would have caused a leak because 'new FileHandle' would have
filled up the symbol tables with junk, but Perl now defends itself
against this sort of abuse (and ungensym is a no-op).

Ian

Thread Previous


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