Well, OK. I guess I was thinking in a perfect world, perl would be in
charge of freeing all out of scope objects. Isn't that one og Java's claims
to fame? Or not, I know littel about Java.
Perl does reference counting, and will "free" all objects that have no
references to them anymore. Image::Magick objects are not pure Perl
objects, however, but an XS wrapper around a C library. The memory
leak can be anywhere inside that XS or C code.
The ImageMagick library has had some memory leaks internally in the
past (which is why I advised using the latest library to see whether
the problem persists), which generally get fixed quite quickly.
While Image::Magick objects look like regular references to Perl
arrays, they're not. Perl only controls the freeing of memory up to
the freeing of the Image::Magick blessed object reference itself.
Everything after that is dealt with in the Image::Magick XS code, and
the ImageMagick library internally, and is (largely) out of the
control of perl, unless the author uses Perl structures in that code
and correctly keeps track of references.
It is quite easy to plug in a C module to perl that leaks memory.
However, that doesn't make it the fault of Perl that there is a leak.
The following little program (which will only report memory correctly
on Linux, really) illustrates that. it uses Inline::C instead of XS,
but the effect is the same: The code that allocates memory and doesn't
hand control of it over to perl, leaks, the code that does allow perl
to clean up, doesn't:
#!/usr/local/bin/perl
use warnings;
use strict;
use Inline 'C';
for my $i (0 .. 9)
{
my $foo = gimmePerlmemory();
print reportmem(), ", ";
}
print "\n";
for my $i (0 .. 9)
{
my $foo = gimmememory();
print reportmem(), ", ";
}
print "\n";
sub reportmem
{
open my $ps, "/proc/self/stat" or die;
seek $ps, 0, 0;
(split ' ', scalar <$ps>)[22] / 1024;
}
__END__
__C__
#include <stdlib.h>
char * gimmememory()
{
return malloc(4096);
}
SV * gimmePerlmemory()
{
return newSVpv("", 4096);
}
And the output is:
5940, 5948, 5948, 5948, 5948, 5948, 5948, 5948, 5948, 5948, 5948,
5948, 5952, 5956, 5960, 5964, 5968, 5972, 5976, 5980, 5984, 5988,
As you can see, the 4 kB of malloc'ed memory is being leaked, while
the 4 kB of newSV memory is neatly being reclaimed. The same goes for
external modules. If they don't clean up their own memory, or they
don't allow Perl to do it, the memory will be leaked.
Martien