I have been working on a perl project at work, and came across a strange memory leak. I have boiled down the source of my problem into a contrived example:
#!/usr/bin/perl
use strict;
use warnings;
# takes: an array reference
# returns: 1
sub g {
my ($a) = @_;
return 1;
}
# takes: nothing
# returns: the result of applying g on an array reference
sub f {
my @a = ('a') x 131072; # allocate roughly a megabyte
return g(\@a);
}
# causes a leak:
#map { f($_) } (1..100000);
# loop equivalent to map, no leak:
#my @b;
#for my $i (1..100000) {
# push @b, f($_);
#}
# causes a leak:
#grep { f($_) } (1..100000);
# loop equivalent to grep, no leak:
#my @b;
#for my $i (1..100000) {
# push @b, $i if f($_);
#}
Uncomment 1 of the 4 blocks of code (beneath the subroutines) at a time and run the script while monitoring its memory usage. On my machine, the code that uses grep or map appear to cause memory leaks, whereas the "loop equivalent"s do not. My perl version is v5.10.1, and I am running Ubuntu.
I believe this could be a bug in perl, but I don't want to jump to a drastic conclusion without another opinion on what could be the cause. Can anyone explain if this behaviour is correct?
Thanks