perlperlapi

Should I call SvREFCNT_dec() on a SV that is not going to be returned to Perl on the stack?


When calling a C function from Perl, for example using Inline::C:

use feature qw(say);
use strict;
use warnings;
use Inline C => './test.c';

say "Calling test()..";
test();
say "Finished.";

where test.c is:

void test() 
{
    SV *sv_variable = newSVpv("test", 0);

    // do something..

    //SvREFCNT_dec(sv_variable); // free variable
    printf( "Returning from test()..\n");
    return;

}

The script seems to work fine whether I call SvREFCNT_dec(sv_variable) or not. According to perlguts:

To free an SV that you've created, call SvREFCNT_dec(SV*). Normally this call is not necessary


Solution

  • Yes, you should decrement the refcount. (If you don't, there are no immediate bad effects, but you've created a memory leak.)

    perlguts probably says this normally isn't necessary because most SVs aren't just used internally in C functions; they're part of structures reachable from Perl space or put on the stack.

    But note that your code structure isn't exception safe: If any function in // do something throws, sv_variable will leak (because SvREFCNT_dec is never reached). This can be fixed by doing:

    SV *sv_variable = sv_2mortal(newSVpv("test", 0));
    

    sv_2mortal is like a deferred SvREFCNT_dec: It will decrement the reference count some time "later".

    (If you're creating an SV from a string literal, newSVpvs("test") is better than newSVpv because it doesn't have to compute the length at runtime.)