I should clarify. The memory does eventually get reclaimed, so this isn't a true memory leak. The memory is just tied up until the final recursive call returns. If the value returned by foo() is large, or if there a large number of recursive calls, then this can cause the system to run out of memory.

I originally ran into this problem when using Exception::Class to handle errors. I had an exception that caused a tail-recursive call to the current function, and this exception was happening repeatedly because there were a lot of invalid records in a row. Exception::Class objects are pretty large, so the system eventually ran out of memory. The code looked something like this:

sub get { my ($self) = @_; my ($record, $e); eval { $record = $self->create_record(); }; if ( $e = Exception::Record::Corrupt->caught() ) { # We got a recoverable error, so skip this record. goto &get; } elsif ( $e = Exception::Class->caught() ) { # Rethrow any generic exception caught and abort. ref $e ? $e->rethrow : die $e; } return $record; }
Anyway, there are plenty of ways to fix this problem. The easiest is to not use tail-recursion, but it *should* work with tail recursion. The odd thing to me is that this problem only occurs when the function call is in the if-conditional.

In reply to Re^2: memory leak when using tail recursion? by juddhuck
in thread memory leak when using tail recursion? by juddhuck

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.