use Test::Weaken qw(leaks);

 # basic leaks detection
 my $leaks = leaks(sub {
                    my $obj = { one => 1,
                                two => [],
                                three => [3,3,3] };
                    return $obj;
 if ($leaks) {
     print "There were memory leaks from test 1!\n";
     printf "%d of %d original references were not freed\n",
         $leaks->unfreed_count(), $leaks->probe_count();
 } else {
     print "No leaks in test 1\n";

 # or with various options
 $leaks = Test::Weaken::leaks(
    { constructor => sub {
        my @array = (42, 711);
        push @array, \@array;  # circular reference
        return \@array;
      destructor  => sub {
        print "This could invoke an object destructor\n";
      ignore  => sub {
        my ($ref) = @_;
        if (some_condition($ref)) {
          return 1;  # ignore
        return 0; # don't ignore
      contents  => sub {
        my ($ref) = @_;
        return extract_more_from($ref);
 if ($leaks) {
     print "There were memory leaks from test 2!\n";
     my $unfreed_proberefs = $leaks->unfreed_proberefs();
     print "These are the probe references to the unfreed objects:\n";
     require Data::Dumper;
     foreach my $ref (@$unfreed_proberefs) {
         print "ref $ref\n";
         print Data::Dumper->Dump([$ref], ['unfreed']);


\*(C`Test::Weaken\*(C' helps detect unfreed Perl data in arrays, hashes, scalars, objects, etc, by descending recursively through structures and watching that everything is freed. Unfreed data is a useless overhead and may cause an application to abend due to lack of memory.

Normally if the last reference to something is discarded then it and anything in it is freed automatically. But this might not occur due to circular references, unexpected global variables or closures, or reference counting mistakes in XSUBs.

\*(C`Test::Weaken\*(C' is named for the strategy used to detect leaks. References are taken to the test objects and all their contents, then those references are weakened and expected to be then freed.

There's options to ignore intentional globals, or include extra associated data held elsewhere, or invoke an explicit destructor. Unfreed parts are reported and can be passed to other modules such as Devel::FindRef to try to discover why they weren't freed.

\*(C`Test::Weaken\*(C' examines structures to an unlimited depth and is safe on circular structures.

Tracking and Children

\*(C`Test::Weaken\*(C' determines the contents of a data structure by the contents of the top object of the test data structure, and recursively into the contents of those sub-parts. The following data types are tracked and their contents examined,

ARRAY each of its values HASH each of its values SCALAR if a reference then the target thing CODE no contents as yet tie ANY the associated tie object from tied()

In an array or hash each scalar value has an independent existence and \*(C`Test::Weaken\*(C' tracks each individually (see \*(L"Array and Hash Keys and Values\*(R" below).

\*(C`CODE\*(C' objects, ie. subroutines, are not examined for children. This is a limitation, because closures do hold internal references to data objects. Future versions of \*(C`Test::Weaken\*(C' might descend into \s-1CODE\s0 objects.

The following types are not tracked by default and not examined for contents,

GLOB IO underlying a file handle FORMAT always global LVALUE

GLOBs are usually either an entry in the Perl symbol table or a filehandle. An \s-1IO\s0 is the file object underlying a filehandle. Perl symbol tables are usually permanent and shouldn't be tracked, but see \*(L"File Handles\*(R" below for tracking open files.

Builtin types added to Perl in the future and not known to \*(C`Test::Weaken\*(C' will not be tracked by default but could be requested with \*(C`tracked_types\*(C' below.

A variable of builtin type \s-1GLOB\s0 may be a scalar which was assigned a \s-1GLOB\s0 value (a scalar-GLOB) or it may simply be a \s-1GLOB\s0 (a pure-GLOB). The issue that arises for \*(C`Test::Weaken\*(C' is that, in the case of a scalar-GLOB, the scalar and the \s-1GLOB\s0 may be tied separately. At present, the underlying tied variable of the scalar side of a scalar-GLOB is ignored. Only the underlying tied variable of the \s-1GLOB\s0 is a child for \*(C`Test::Weaken\*(C''s purposes.

Returns and Exceptions

The methods of \*(C`Test::Weaken\*(C' do not return errors. Errors are always thrown as exceptions.


By default, \*(C`Test::Weaken\*(C' exports nothing. Optionally, \*(C`leaks()\*(C' may be requested in usual \*(C`Exporter\*(C' style (see Exporter). (And \*(C`poof()\*(C' from \*(L"\s-1OLD\s0 \s-1FUNCTIONS\s0\*(R" too if desired.)

use Test::Weaken 'leaks'; # import my $tester = leaks (...);



my $leaks = Test::Weaken::leaks( { constructor => sub { Buggy_Object->new() }, destructor => \&destroy_buggy_object, } ); if ($leaks) { print "There are leaks\n"; }

Check for leaks in the object created by the constructor function and return either an evaluated \*(C`Test::Weaken\*(C' object instance if there are leaks, or Perl false if there are no leaks.

Instances of the \*(C`Test::Weaken\*(C' class are called testers. An evaluated tester is one on which the tests have been run and for which results are available.

Users who only want to know if there were unfreed data objects can check the return value of \*(C`leaks()\*(C' for Perl true or false. Arguments to \*(C`leaks()\*(C' are passed as a hashref of named arguments. \*(C`leaks()\*(C' can also be called in a \*(L"short form\*(R", where the constructor and destructor are passed directly as code references. The \*(C`constructor\*(C' argument is required. Its value must be a coderef returning a reference to the test data structure. my $leaks = leaks ({ constructor => sub { return Some::Object->new(123); }, }); For \*(L"short form\*(R" the constructor coderef is the first argument, leaks (sub { return Some::Object->new(123); }); If the constructor returns a list of objects then all are checked. leaks (sub { return (Foo->new(), Bar->new()); }); Usually this is when two objects are somehow inter-related and should weaken away together, or perhaps sub-parts of an object not reached by the contents tracing (or see \*(C`contents\*(C' below for a more general way to reach such sub-parts.) An optional destructor is called just before \*(C`Test::Weaken\*(C' tries to free everything. Some test objects or structures might require explicit destruction when they're to be freed. \*(C`destructor\*(C' is called with the objects returned by the constructor &$destructor ($obj, ...) For example, leaks ({ constructor => sub { return make_some_thing() }, destructor => sub { my ($thing) = @_; delete $thing->{'circular_ref'}; }, }); For \*(L"short form\*(R" the destructor is an optional second argument, leaks (sub { Foo->new }, sub { my ($foo) = @_; $foo->destroy; }); \*(C`destructor_method\*(C' is called as a method on each object returned by the constructor, $obj->$methodname(); For example if the constructed object (or objects) require an explicit \*(C`$foo->destroy()\*(C' then leaks ({ constructor => sub { Foo->new }, destructor_method => 'destroy' }); If both \*(C`destructor\*(C' and \*(C`destructor_method\*(C' are given then \*(C`destructor_method\*(C' calls are first, then \*(C`destructor\*(C'. An explicit destructor may be needed for things like toplevel windows in \s-1GUI\s0 toolkits such as Wx and Gtk (and perhaps also some main loop iterations if actual destruction is delayed). Some object-oriented tree structures may need explicit destruction too if parent and child nodes keep hard references to each other, though it's usually more convenient if child->parent is only a weak reference. (See also Object::Destroyer.) Ignore some things. When a thing is ignored it's not tracked for leaks and its contents are not examined. \*(C`ignore\*(C' and \*(C`ignore_preds\*(C' take predicate functions. If any of them return true then the thing $ref refers to is ignored. $bool = &$coderef ($ref); For example sub ignore_all_tied_hashes { my ($ref) = @_; return (ref $ref eq 'HASH' && defined (tied %$ref)); } my $tester = Test::Weaken::leaks( { constructor => sub { MyObject->new() }, ignore => \&ignore_all_tied_hashes, }); \*(C`ignore_class\*(C' and \*(C`ignore_classes\*(C' ignore blessed objects which are of the given class or classes. For example, my $leaks = Test::Weaken::leaks( { constructor => sub { MyObject->new() }, ignore_class => 'My::Singleton', }

my $leaks = Test::Weaken::leaks( { constructor => sub { MyObject->new() }, ignore_classes => [ 'My::Singleton', 'My::PrinterDriver' ], } Objects are checked with blessed($ref) && $ref->isa($classname) which reaches any class-specific \*(C`isa()\*(C' in the object in the usual way. That allows classes to masquerade or have a dynamic \*(L"isa\*(R". That's normally fine and can be highly desirable in things like lazy loaders. \*(C`ignore_object\*(C' and \*(C`ignore_objects\*(C' ignore the particular things referred to by the each given $ref. For example, my $leaks = Test::Weaken::leaks( { constructor => sub { MyObject->new() }, ignore_object => \%global_data, }

my $leaks = Test::Weaken::leaks( { constructor => sub { MyObject->new() }, ignore_objects => [ $obj1, $obj2 ], } For both \*(C`ignore_object\*(C' and \*(C`ignore_objects\*(C' any \*(C`undef\*(C's among the refs are ignored. This is handy if a global might or might not have been initialized yet. These options are called \*(L"object\*(R" because they're most often used with blessed objects, but unblessed things are fine too. \*(C`ignore\*(C' callbacks should not change the contents of $ref. Doing so might cause an exception, an infinite loop, or erroneous results. See \*(L"Debugging Ignore Subroutines\*(R" for a little help against bad \*(C`ignore\*(C'. When comparing references in a predicate it's good to use \*(C`Scalar::Util::refaddr()\*(C'. Plain \*(C`$ref==$something\*(C' can be tricked if $ref is an object with overloaded numize or \*(C`==\*(C' (see overload). Another way to ignore is let globals etc go through as leaks and then filter them from the \*(C`$leaks->unfreed_proberefs()\*(C' afterwards. The benefit of \*(C`ignore\*(C' is that it excludes object contents too.


An optional \*(C`contents\*(C' function can tell \*(C`Test::Weaken\*(C' about additional Perl data objects which should be checked. sub my_extra_contents { my ($ref) = @_; if (blessed($ref) && $ref->isa('MyObject')) { return $ref->data, $ref->moredata; } else { return; } } my $leaks = Test::Weaken::leaks( { constructor => sub { return MyObject->new }, contents => \&my_extra_contents }); The given $coderef is called for each Perl data object. It should return a list of additional Perl data objects, or an empty list if no extra contents. @extra_contents = &$coderef ($ref); \*(C`contents\*(C' allows OOPery such as \*(L"inside-out\*(R" where object contents are held separately. It can also be used on wrappers for C-code objects where some of the contents of a widget etc are not in Perl level structures but only available through object method calls etc. \*(C`contents\*(C' and \*(C`ignore\*(C' can be used together. \*(C`ignore\*(C' is called first and if not ignored then \*(C`contents\*(C' is called.


Optional \*(C`tracked_types\*(C' is an arrayref of additional builtin types to track. my $test = Test::Weaken::leaks( { constructor => sub { my $obj = MyObject->new; return $obj; }, tracked_types => ['GLOB'], } ); The default tracking is per \*(L"Tracking and Children\*(R" above. The additional types which may be tracked are GLOB IO FORMAT LVALUE These names are per \*(C`reftype()\*(C' of Scalar::Util. See \*(L"File Handles\*(R" below for setting up to track GLOBs as filehandles.


my $tester = Test::Weaken::leaks( sub { Buggy_Object->new() } ); if ($tester) { my $unfreed_proberefs = $tester->unfreed_proberefs(); foreach my $ref (@$unfreed_proberefs) { print "unfreed: $ref\n"; } }

Return an arrayref of references to unfreed data objects. Throws an exception if there is a problem, for example if the tester has not yet been evaluated.

The return value can be examined to pinpoint the source of a leak or produce statistics about unfreed data objects.


my $tester = Test::Weaken::leaks( sub { Buggy_Object->new() } ); if ($tester) { printf "%d objects were not freed\n", $tester->unfreed_count(); }

Return the count of unfreed data objects. This is the length of the \*(C`unfreed_proberefs()\*(C' arrayref. Throws an exception if there is a problem, for example if the tester has not yet been evaluated.


my $tester = Test::Weaken::leaks( { constructor => sub { Buggy_Object->new() }, destructor => \&destroy_buggy_object, } ); next TEST if not $tester; printf "%d of %d objects were not freed\n", $tester->unfreed_count(), $tester->probe_count();

Return the total number of probe references in the test, including references to freed data objects. This is the count of probe references after \*(C`Test::Weaken\*(C' was finished finding the descendants of the test structure reference, but before \*(C`Test::Weaken\*(C' called the test structure destructor or reset the test structure reference to \*(C`undef\*(C'. Throws an exception if there is a problem, for example if the tester has not yet been evaluated.


Most users can skip this section. The plumbing methods exist to satisfy object-oriented purists, and to accommodate the rare user who wants to access the probe counts even when the test did find any unfreed data objects.


my $tester = Test::Weaken->new( sub { My_Object->new() } ); my $unfreed_count = $tester->test(); my $proberefs = $tester->unfreed_proberefs(); printf "%d of %d objects freed\n", $unfreed_count, $tester->probe_count();

The \*(L"new\*(R" method takes the same arguments as the \*(L"leaks\*(R" method, described above. Unlike the \*(L"leaks\*(R" method, it always returns an unevaluated tester. An unevaluated tester is one on which the test has not yet been run and for which results are not yet available. If there are any problems, the \*(L"new\*(R" method throws an exception.

The \*(L"test\*(R" method is the only method that can be called successfully on an unevaluated tester. Calling any other method on an unevaluated tester causes an exception to be thrown.


my $tester = Test::Weaken->new( { constructor => sub { My_Object->new() }, destructor => \&destroy_my_object, } ); printf "There are %s\n", ( $tester->test() ? 'leaks' : 'no leaks' );

Converts an unevaluated tester into an evaluated tester. It does this by performing the test specified by the arguments to the \*(L"new\*(R" constructor and recording the results. Throws an exception if there is a problem, for example if the tester had already been evaluated.

The \*(L"test\*(R" method returns the count of unfreed data objects. This will be identical to the length of the array returned by \*(L"unfreed_proberefs\*(R" and the count returned by \*(L"unfreed_count\*(R".


File Handles

File handles are references to GLOBs and by default are not tracked. If a handle is a package global like \*(C`open FH, "</file/name"\*(C' then that's probably what you want. But if you use anonymous handles either from the Symbol module or Perl 5.6 autovivified then it's good to check the handle is freed. This can be done by asking for \s-1GLOB\s0 and \s-1IO\s0 in \*(C`tracked_types\*(C', and extracting the \s-1IO\s0 from any \s-1GLOB\s0 encountered,

sub contents_glob_IO { my ($ref) = @_; if (ref($ref) eq 'GLOB') { return *$ref{IO}; } else { return; } }

my $leaks = Test::Weaken::leaks ({ constructor => sub { return MyFileObject->new }, contents => \&contents_glob_IO, tracked_types => [ 'GLOB', 'IO' ], });

It's good to check the \s-1IO\s0 too since it's possible for a reference elsewhere to keep it alive, in particular a Perl-level \*(L"dup\*(R" can make another handle \s-1GLOB\s0 pointing to that same \s-1IO\s0,

open my $dupfh, '<', $fh; # $dupfh holds and uses *$fh{IO}

See Test::Weaken::ExtraBits for such a \*(C`contents_glob_IO()\*(C', if you want to use a module rather than copying couple of lines for that function.

Array and Hash Keys and Values

As noted above each value in a hash or array is a separate scalar and is tracked separately. Usually such scalars are only used in their containing hash or array, but it's possible to hold a reference to a particular element and \*(C`leaks()\*(C' can notice if that causes it to be unfreed.

my %hash = (foo => 123); my $ref = \$hash{'foo'}; # ref to hash value

It's possible to put specific scalars as the values in a hash or array. They might be globals or whatever. Usually that would arise from \s-1XSUB\s0 code, but Array::RefElem can do the same from Perl code,

use Array::RefElem 'av_store'; my $global; my @array; av_store (@array, 0, $global);

In \s-1XSUB\s0 code a little care is needed that refcounts are correct after \*(C`av_store()\*(C' or \*(C`hv_store()\*(C' takes ownership of one count etc. In all cases \*(C`Test::Weaken\*(C' can notice when an array or hash element doesn't destroy with its container. \*(C`ignore\*(C' etc will be needed for those which are intentionally persistent.

Hash keys are not separate scalars. They're strings managed entirely by the hash and there's nothing separate for \*(C`Test::Weaken\*(C' to track.

Tie::RefHash and similar which allow arbitrary objects as keys of a hash do so by using the object \*(C`refaddr()\*(C' internally as the string key but presenting objects in \*(C`keys()\*(C', \*(C`each()\*(C', etc. As of Tie::RefHash 1.39 and Tie::RefHash::Weak 0.09 those two modules hold the key objects within their tie object and therefore those key objects are successfully reached by \*(C`Test::Weaken\*(C' for leak checking in the usual way.

Tracing Leaks


\*(C`Test::Weaken\*(C' makes tracing leaks easier, but avoidance is still by far the best way, and \*(C`Test::Weaken\*(C' helps with that. You need to use test-driven development, Test::More, modular tests in a \*(C`t/\*(C' subdirectory, and revision control. These are all very good ideas for many other reasons.

Make \*(C`Test::Weaken\*(C' part of your test suite. Test frequently, so that when a leak occurs, you'll have a good idea of what changes were made since the last successful test. Often, examining these changes is enough to tell where the leak was introduced.

Adding Tags

The \*(L"unfreed_proberefs\*(R" method returns an array containing probes to the unfreed data objects. This can be used to find the source of leaks. If circumstances allow it, you might find it useful to add \*(L"tag\*(R" elements to arrays and hashes to aid in identifying the source of a leak.

Using Referent Addresses

You can quasi-uniquely identify data objects using the referent addresses of the probe references. A referent address can be determined by using \*(C`refaddr()\*(C' from Scalar::Util. You can also obtain the referent address of a reference by adding 0 to the reference.

Note that in other Perl documentation, the term \*(L"reference address\*(R" is often used when a referent address is meant. Any given reference has both a reference address and a referent address. The reference address is the reference's own location in memory. The referent address is the address of the Perl data object to which the reference refers. It is the referent address that interests us here and, happily, it is the referent address that both zero addition and refaddr return.

Other Techniques

Sometimes, when you are interested in why an object is not being freed, you want to seek out the reference that keeps the object's refcount above 0. Devel::FindRef can be useful for this.

More About Quasi-Unique Addresses

I call referent addresses \*(L"quasi-unique\*(R", because they are only unique at a specific point in time. Once an object is freed, its address can be reused. Absent other evidence, a data object with a given referent address is not 100% certain to be the same data object as the object that had the same address earlier. This can bite you if you're not careful.

To be sure an earlier data object and a later object with the same address are actually the same object, you need to know that the earlier object will be persistent, or to compare the two objects. If you want to be really pedantic, even an exact match from a comparison doesn't settle the issue. It is possible that two indiscernable (that is, completely identical) objects with the same referent address are different in the following sense: the first data object might have been destroyed and a second, identical, object created at the same address. But for most practical programming purposes, two indiscernable data objects can be regarded as the same object.

Debugging Ignore Subroutines


$tester = Test::Weaken::leaks( { constructor => sub { MyObject->new() }, ignore => Test::Weaken::check_ignore( \&ignore_my_global ), } );

$tester = Test::Weaken::leaks( { constructor => sub { DeepObject->new() }, ignore => Test::Weaken::check_ignore( \&cause_deep_problem, 99, 0, $reporting_depth ), } );

It can be hard to determine if \*(C`ignore\*(C' callback subroutines are inadvertently modifying the test structure. The Test::Weaken::check_ignore static method is provided to make this task easier. Test::Weaken::check_ignore constructs a debugging wrapper from four arguments, three of which are optional. The first argument must be the ignore callback that you are trying to debug. This callback is called the test subject, or lab rat.

The second, optional argument, is the maximum error count. Below this count, errors are reported as warnings using Carp::carp. When the maximum error count is reached, an exception is thrown using Carp::croak. The maximum error count, if defined, must be an number greater than or equal to 0. By default the maximum error count is 1, which means that the first error will be thrown as an exception.

If the maximum error count is 0, all errors will be reported as warnings and no exception will ever be thrown. Infinite loops are a common behavior of buggy lab rats, and setting the maximum error count to 0 will usually not be something you want to do.

The third, optional, argument is the compare depth. It is the depth to which the probe referents will be checked, as described below. It must be a number greater than or equal to 0. If the compare depth is 0, the probe referent is checked to unlimited depth. By default the compare depth is 0.

This fourth, optional, argument is the reporting depth. It is the depth to which the probe referents are dumped in check_ignore's error messages. It must be a number greater than or equal to -1. If the reporting depth is 0, the object is dumped to unlimited depth. If the reporting depth is -1, there is no dump in the error message. By default, the reporting depth is -1.

Test::Weaken::check_ignore returns a reference to the wrapper callback. If no problems are detected, the wrapper callback behaves exactly like the lab rat callback, except that the wrapper is slower.

To discover when and if the lab rat callback is altering its arguments, Test::Weaken::check_ignore compares the test structure before the lab rat is called, to the test structure after the lab rat returns. Test::Weaken::check_ignore compares the before and after test structures in two ways. First, it dumps the contents of each test structure using Data::Dumper. For comparison purposes, the dump using Data::Dumper is performed with \*(C`Maxdepth\*(C' set to the compare depth as described above. Second, if the immediate probe referent has builtin type \s-1REF\s0, Test::Weaken::check_ignore determines whether the immediate probe referent is a weak reference or a strong one.

If either comparison shows a difference, the wrapper treats it as a problem, and produces an error message. This error message is either a Carp::carp warning or a Carp::croak exception, depending on the number of error messages already reported and the setting of the maximum error count. If the reporting depth is a non-negative number, the error message includes a dump from Data::Dumper of the test structure. \*(C`Data::Dumper\*(C''s \*(C`Maxdepth\*(C' for reporting purposes is the reporting depth as described above.

A user who wants other features, such as deep checking of the test structure for strengthened references, can easily copy \*(C`check_ignore()\*(C' from the \*(C`Test::Weaken\*(C' source and hack it up. \*(C`check_ignore()\*(C' is a static method that does not use any \*(C`Test::Weaken\*(C' package resources. The hacked version can reside anywhere, and does not need to be part of the \*(C`Test::Weaken\*(C' package.

XSUB Mortalizing

When a C code \s-1XSUB\s0 returns a newly created scalar it should \*(L"mortalize\*(R" so the scalar is freed once the caller has finished with it. See \*(L"Reference Counts and Mortality\*(R" in perlguts. Failing to do so leaks memory.

SV *ret = newSViv(123); sv_2mortal (ret); /* must mortalize */ XPUSHs (ret);

\*(C`Test::Weaken\*(C' can check this by taking a reference to the returned scalar,

my $leaks = leaks (sub { return \( somexsub() ); }); if ($leaks) ...

Don't store to a new local scalar and then return that since doing so will only check the local scalar, not the one made by \*(C`somexsub()\*(C'.

If you want the value for further calculations then first take a reference to the return and then look through that for the value.

leaks (sub { my $ref = \( somexsub() ); my $value = $$ref; # ... do something with $value return $ref; });

If an \s-1XSUB\s0 returns a list of values then take a reference to each as follows. This works because \*(C`map\*(C' and \*(C`for\*(C' make the loop variable ($_ or named) an alias to each value successively (see \*(L"map\*(R" in perlfunc and \*(L"Foreach Loops\*(R" in perlsyn).

leaks (sub { return [ map {\$_} somexsub() ]; });

# or with a for loop leaks (sub { my @refs; foreach my $value (somexsub()) { push @refs, \$value; } return \@refs; });

Don't store a returned list to an array (named or anonymous) since this copies into new scalars in that array and the returned ones from \*(C`somexsub()\*(C' then aren't checked.

If you want the returned values for extra calculations then take the references first and look through them for the values, as in the single case above. For example,

leaks (sub { my @refs = map {\$_} somexsub(); my $first_ref = $refs[0] my $value = $$first_ref; # ... do something with $value return \@refs; });

An \s-1XSUB\s0 might deliberately return the same scalar each time, perhaps a pre-calculated constant or a global variable it maintains. In that case the scalar intentionally won't weaken away and this \*(C`leaks()\*(C' checking is not applicable.

Returning the same scalar every time occurs in pure Perl too with an anonymous constant subr such as created by the \*(C`constant\*(C' module (see constant). This is unlikely to arise directly, but might be seen through a scalar ref within an object etc.

# FOO() returns same scalar every time *FOO = sub () { 123 };

# same from the constant module use constant BAR => 456;

It's up to an \s-1XSUB\s0 etc how long return values are supposed to live. But generally if the code has any sort of \*(C`newSV()\*(C' or \*(C`sv_newmortal()\*(C' etc to make a new scalar as its return then that ought to weaken away.

The details of an \s-1XSUB\s0 return are often hidden in a typemap file for brevity and consistency (see \*(L"The Typemap\*(R" in perlxs). The standard typemap conversions of Extutils/typemap are easy to use correctly. But code with explicit \*(C`PUSHs()\*(C' etc is worth checking. The reference counting rules for \*(C`av_push()\*(C' etc are slightly subtle too if building nested structures in \s-1XS\s0. Usually missing mortalizing or ref count sinking will leak objects which \*(C`Test::Weaken\*(C' can detect. Too much mortalizing or ref count sinking will cause negative refcounts and probable segfaults.


The following \*(C`poof()\*(C' was from \*(C`Test::Weaken\*(C' 1.0 and has been superseded in 2.0 by \*(C`leaks()\*(C' which is easier to use. Check that $obj returned by the given constructor subroutine is freed when weakened. This is the same as \*(C`leaks()\*(C' except for the style of the return values. In scalar context the return is a count of unfreed references. If everything is freed then this is 0. my $unfreed_count = Test::Weaken::poof(sub { return [1,2,3] }); if ($unfreed_count == 0 { print "No leaks\n"; } else { print "There were leaks\n"; } In array context the return is four values my ($weak_count, $strong_count, $weak_unfreed_aref, $strong_unfreed_aref) = Test::Weaken::poof (sub { return $obj });

$weak_count count of weak refs examined $strong_count count of strong refs examined $weak_unfreed_aref arrayref of unfreed weak refs $strong_unfreed_aref arrayref of unfreed strong refs The counts are total references examined. The arrayrefs give the unfreed ones. A distinction is made between strong references and weak references in the test structure. If there's no leaks then both $weak_unfreed_aref and $strong_unfreed_aref are empty arrays. There's usually not much interest in whether an unfreed thing was from a weak or strong reference. In the new \*(C`leaks()\*(C' the \*(C`unfreed_proberefs()\*(C' gives both together. The could be separated there by checking \*(C`isweak()\*(C' on each if desired.



\*(C`Test::Weaken\*(C' first recurses through the test structure. Starting from the test structure reference, it examines data objects for children recursively, until it has found the complete contents of the test structure. The test structure is explored to unlimited depth. For each tracked Perl data object, a probe reference is created. Tracked data objects are recorded. In the recursion, no object is visited twice, and infinite loops will not occur, even in the presence of cycles.

Once recursion through the test structure is complete, the probe references are weakened. This prevents the probe references from interfering with the normal deallocation of memory. Next, the test structure destructor is called, if there is one.

Finally, the test structure reference is set to \*(C`undef\*(C'. This should trigger the deallocation of the entire contents of the test structure. To check that this happened, \*(C`Test::Weaken\*(C' dereferences the probe references. If the referent of a probe reference was deallocated, the value of that probe reference will be \*(C`undef\*(C'. If a probe reference is still defined at this point, it refers to an unfreed Perl data object.

Why the Test Structure is Passed Via a Closure

\*(C`Test::Weaken\*(C' gets its test structure reference indirectly, as the return value from a test structure constructor. Why so roundabout?

Because the indirect way is the easiest. When you create the test structure in \*(C`Test::Weaken\*(C''s calling environment, it takes a lot of craft to avoid leaving unintended references to the test structure in that calling environment. It is easy to get this wrong. Those unintended references will create memory leaks that are artifacts of the test environment. Leaks that are artifacts of the test environment are very difficult to sort out from the real thing.

The closure-local strategy is the easiest way to avoid leaving unintended references to the contents of Perl data objects. Using the closure-local strategy means working entirely within a closure, using only data objects local to that closure. Data objects local to a closure will be destroyed when the closure returns, and any references they held will be released. The closure-local strategy makes it relatively easy to be sure that nothing is left behind that will hold an unintended reference to any of the contents of the test structure.

Nothing prevents a user from subverting the closure-local strategy. A test structure constructor can return a reference to a test structure created from Perl data objects in any scope the user desires.


Jeffrey Kegler


Please report any bugs or feature requests to \*(C`bug-test-weaken at\*(C', or through the web interface at


You can find documentation for this module with the perldoc command.

perldoc Test::Weaken

You can also look for information at:

  • AnnoCPAN: Annotated \s-1CPAN\s0 documentation <>

  • \s-1CPAN\s0 Ratings <>

  • \s-1RT:\s0 \s-1CPAN\s0's request tracker <>

  • Search \s-1CPAN\s0 <>

RELATED TO Test::Weaken…

Test::Weaken::ExtraBits, miscellaneous extras

Test::Weaken::Gtk2, extras for use with Gtk2-Perl

Scalar::Util, Scalar::Util::Instance

\*(C`Test::Weaken\*(C' at this point is robust and has seen extensive use. Its tracking of memory is careful enough that it has even stumbled upon a bug in perl itself <>.


Thanks to jettero, Juerd, morgon and perrin of Perlmonks for their advice. Thanks to Lincoln Stein (developer of Devel::Cycle) for test cases and other ideas. Kevin Ryde made many important suggestions and provided the test cases which provided the impetus for the versions 2.000000 and after. For version 3.000000, Kevin also provided patches.


Copyright 2012 Jeffrey Kegler, all rights reserved.

Copyright 2012 Kevin Ryde

This program is free software; you can redistribute it and/or modify it under the same terms as Perl 5.10.