<?xml version="1.0" encoding="windows-1252"?>
<node id="560083" title="perlembed: mortalize an AV, get &quot;Attempt to free unreferenced scalar&quot; - don't mortalize, leaks memory" created="2006-07-10 03:23:20" updated="2006-07-09 23:23:20">
<type id="115">
perlquestion</type>
<author id="236234">
edan</author>
<data>
<field name="doctext">
I am trying to call a perl subroutine from C, passing it an array ref.  I am not managing to do this correctly without leaking memory.  Can someone please tell me why?
&lt;p/&gt;
If I mortalize the "AV" (commented line below), I get "Attempt to free unreferenced scalar".  But If I don't, I'm leaking memory, as evidenced by [cpan://Devel::Leak] (though for some reason it isn't telling me that the AV is left around, rather the SV containing the name of the subroutine being called, "MyModule::test" in the below code - weird).  It seems like I should be mortalizing it, but I can't figure out why it's getting "over-decremented" when I do.
&lt;p/&gt;

&lt;code&gt;
    dSP;
    ENTER;
    SAVETMPS;
    PUSHMARK(SP);
    AV *arr = newAV();
    // AV *arr = (AV *) sv_2mortal((SV *) newAV());
    av_push( arr, sv_2mortal(newSVpv("test", 0)));
    XPUSHs(sv_2mortal(newRV((SV *)arr)));
    PUTBACK;
    call_sv(sv_2mortal(newSVpv("MyModule::subroutine", 0)), G_SCALAR);
    SPAGAIN;
    SV *retval = POPs;
    PUTBACK;
    FREETMPS;
    LEAVE;

&lt;/code&gt;

&lt;p/&gt;

Can someone help clear this up for me, please?

&lt;p/&gt;
&lt;b&gt;Update:&lt;/b&gt; I have tinkered some more, and found a formula that seems to work, but I don't understand why.  The following sub-snippet appears to work:
&lt;p/&gt;
&lt;code&gt;
AV *arr = (AV *) sv_2mortal((SV *) newAV());
av_push( arr, newSVpv("test", 0));
&lt;/code&gt;
&lt;p/&gt;
So I'm not supposed to mortalize the scalars that I push onto the array?  Why is that?  It makes my problem disappear, which I like, but I don't understand it, which I don't like.  Any further thoughts are appreciated.
&lt;p/&gt;

&lt;div class="pmsig"&gt;&lt;div class="pmsig-236234"&gt;
--&lt;br /&gt;[edan]&lt;br /&gt;&lt;br /&gt;

&lt;/div&gt;&lt;/div&gt;</field>
</data>
</node>
