Search code examples
memory-leaksperlhashrefhash-reference

Does returning a ref to a hash declared in subroutine causes memory leak?


Is using my %data; below okay or should I switch to my $data={}; ?

#!/usr/bin/perl -wT
use strict;
use JSON;

sub makeJson {
        my %data;

        $data{kib} = 1;
        $data{games} = {
                0 => [],
                1 => [qw(a b c d e)],
        };

        return \%data;
}

my $x = makeJson();
print encode_json($x) . "\n";

I'm confused because -

If the makeJson() is called several times - and the my %data; is allocated at stack and then that address is being returned - wouldn't that be a memory leak or maybe not a "leak", but a "problem"? Because there would be memory allocated at the stack, which is still referenced and thus can not be deallocated.

And other way around: if I have a subroutine returning a hash reference, which is better to use my %data; (faster, because preallocated by compiler?) or my $data={}; ?


Solution

  • Perl is not C.

    That's the actual answer to your question, but I'll expand a bit.

    Perl is not C in that Perl does not have automatic variables. It has lexical and dynamic variables and that's it.

    Perl is not C in that Perl does memory management so you (mostly) don't have to. Absent circular references, memory leaks don't occur.

    Perl is not C in that the cost of being an interpreted language dominates most performance calculations, and so micro-optimizing hashes versus hashrefs is almost always irrelevant.

    Use whichever construct more naturally expresses your intention. Neither leaks memory more than the other; Amdahl can worry about the tiny performance differences. Perl is not C.