According to the Learning Perl book, truncating an array does not recover its memory. To feee memory I need to undef the array like this undef(@array). It also says that the memory doesn't always get free because not many operating systems support this. I find this strange as I've never had this problem in other languages.

I'm using Win2K and not much memory gets free when I undef my array. When I run the script below the @array takes ~76,000K in memory when I hit the breakpoint. After undef(@array) gets executed the memory only goes down to ~72,000K. If I continue the loop and watch memory it'll fluctuate between these two numbers.

Is there another way to free the memory? Does anyone else find this behavior strange? I must be missing something, perhaps some monks can enlighten me.

Thanks.

use strict; use warnings; print $$; my @array; my $i = 0; while (1) { $array[$i++]= '1234567890'; if ($i == 1_000_000) { undef(@array); #BREAKPOINT HERE $i = 0; } }
UPDATE
The memory is even kept after the array goes out of scope.
use strict; use warnings; print "PID: $$\n"; { my @array; my $i = 0; while ($i <= 1_000_000) { $array[$i++]= '1234567890';# for([0..1_000_000]); if ($i == 1_000_000) { undef(@array); } } } print "END\n"; # BREAKPOINT HERE, MEMORY IS STILL NOT FREE

In reply to Freeing memory used by arrays by monktim

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.