andal has asked for the wisdom of the Perl Monks concerning the following question:

Somehow, in the last few days I stumble more over perl peculiarities, than in last few years :)

Again. I wanted to check how perl handles memory when I use substr($a, 0, 1) = ''. So I've used Devel::Peek to try the following code

use Devel::Peek 'Dump'; use strict; my $a = "test"; substr($a, 0, 2) = ''; Dump $a;
To my surprise it has produced the output
SV = PV(0x22d3088) at 0x22f1968
  REFCNT = 2
  FLAGS = (PADMY,POK,OOK,pPOK)
  OFFSET = 2
  PV = 0x22e26b2 ( "t\2" . ) "st"\0
  CUR = 2
  LEN = 6
REFCNT is 2! Why? At first I thought, that this has something to do with the Devel::Peek, but after checking few other situations, I'm sure, that this happens only when I use substr to modify the content of the variable. Is there some internal reason for incrementing the reference count for the variable, or it is just a bug?

Replies are listed 'Best First'.
Re: is this a memory leak or do I miss something?
by Anonymous Monk on Oct 28, 2010 at 08:13 UTC
Re: is this a memory leak or do I miss something?
by jwkrahn (Abbot) on Oct 28, 2010 at 08:52 UTC

    What happens when you use a four argument substr?

    substr $a, 0, 2, '';
      perl -MDevel::Peek -e " my $a = q!1234!; Dump $a; " perl -MDevel::Peek -e " my $a = q!1234!; substr$a,0,2,q!!; Dump $a; " perl -MDevel::Peek -e " my $a = q!1234!; substr($a,0,2)=q!!; Dump $a; +" perl -MDevel::Peek -e " my $a = q!1234!; substr($a,0,2)=q!!; substr$a, +0,2,q!!; Dump $a; " perl -MDevel::Peek -e " my $a = q!1234!; substr$a,0,2,q!!; substr($a,0 +,2)=q!!; Dump $a; "
      on 5.10.0 / 5.8.9 5.12.2 my observations match those of the bug reports, each lvalue increases the refcount but there is no actual memory leak
        Yep. I also don't see any memory leak. I guess, that this extra locking is essential for the work of functions as lvalue. pos and vec cause the same behaviour. The variable is locked as many times as there are usages of function as lvalue. Then it is not a bug, but just a feature.

      On my machine, then I get refcount 1

      SV = PVIV(0x81f14ec) at 0x81fb5a8 REFCNT = 1 FLAGS = (PADMY,POK,OOK,pPOK) IV = 2 (OFFSET) PV = 0x81f5e22 ( "te" . ) "st"\0 CUR = 2 LEN = 6
      Machine:
      This is perl, v5.10.1 (*) built for i686-linux-gnu-thread-multi
      (with 40 registered patches, see perl -V for more detail)