Why does the following code leak memory?

 void leak()
 {
   ENTER;
   SAVETMPS;

   SV* node_var = get_sv("main::SOMETHING", TRUE);
   save_item(node_var);
   SV* obj_ref = sv_setref_iv(newSV(0), "My::Package", 0xdeadbeef);
   SvSetSV(node_var, obj_ref);
   SvREFCNT_dec(obj_ref);

   /* do stuff */

   FREETMPS;
   LEAVE;
 }

I run that in a while(1) loop and it leaks memory like crazy. I
originally didn't have the SvREFCNT_dec() in there, because I thought
SvSetSV would take ownership of the source SV, but I was wrong. It
tries to be a value copy, so that makes sense to me.

Commenting out the save_item() "fixes" the leak. But why? I don't
understand at all what the refcounting implications of save_item()
are. I want to be able to change $main::SOMETHING to my local value,
do some stuff (between SvREFCNT_dec and FREETMPS), and then have its
previous value restored. The above code works, in that the value is
set to what I want it to be at all times, but the save_item triggers a
leak.

Reply via email to