As my understanding of memory management continues to evolve, I wonder if
one or more of you could comment on the following questions:

Perlguts states in the context of av_fetch that "If lval is set then the
fetch will be part of a store."  I don't understand what that means.  I
often use av_fetch followed by av_store, and I wonder if I am missing a
shortcut or an important piece of book keeping therein by not setting lval
to true? I typically just do this:

---8<-----------
svNewVal = *av_fetch(avImage, i, 0);   
svREFCNT_inc(svNewVal);
if (av_store(avGrid, i, svNewVal) == NULL ) 
{
  svREFCNT_inc(svNewVal);  
} 
---8<-----------

Any problem there?

Perlguts also states that I must increment the reference count myself when
using av_store, and decrement it if the store fails.  May I presume then,
from the silence on this issue elsewhere in perlguts, that I do not need to
manage the reference counts myself when using av_fetch and av_push?  In
other words, is the fetching and storing in the following example, without
any reference count increments or decrements, ok (this does not leak memory
as far as I can tell, but I wonder if any experts have any critique of
this):

---8<-----------
SV* myFunction(SV* svImage, int iChannel, int iThreshold)
{
  AV *avImage, *avMask;
  int i, iImageA;
  SV *r;
  for (i=0; i<(iImageA+1)/3; i++)
    {
      if (SvIV(*av_fetch(avImage, i*3+iChan, 0)) > iThresh)
        {
          r = *av_fetch(avImage, i*3, 0);
        } else
        {
          r = newSViv(0);
        }
        av_push(avMask, r);
    }
 return newRV_noinc((SV*)(avMask));
}
---8<-----------

As Dan Sugalski described this situation earlier:

*) There's a pointer to an SV in an array
*) You fetch the pointer out of the array. Now both you and the array have 
a pointer to the same SV
*) You push the pointer onto the new array. Now you and both arrays have 
pointers to the same SV.

But it appears that the push and fetch macros are taking care of the
reference counts themselves, since this does not leak memory.  Is that
right?

Eric

Reply via email to