Reference counting (and getting it right) is one least well documented parts
of the perl API. I'm never sure if I have it right. But:

On Mon, Jul 21, 2003 at 12:40:48PM -0600, Shane Corgatelli wrote:

>    hash = (HV*)SvRV( col_vals );
>    num_keys = hv_iterinit( hash );
>    for ( i = 0; i < num_keys; i++ ) {
>       hash_entry = hv_iternext( hash );
>       sv_key     = hv_iterkeysv( hash_entry );
>       sv_val     = hv_iterval( hash, hash_entry );
> 
>       sv_setpvn( sv_new_key, "_col_", 5 );
>       sv_catsv( sv_new_key, sv_key );
>       key = SvPV( sv_new_key, keylen );
> 
>       hv_store( members, key, keylen, sv_val, 0 );
>    }
>    hv_iterinit( hash );
>    return;
> }
> 
> When I run this, I get 'Attempt to free unreferenced scalar' warnings.  If I 
> try to run it multiple times I will eventually get segmentation fault.  So 
> after reading perlguts and scanning this list I changed the hv_store call to 
> be:
> 
>       hv_store( members, key, keylen, SvREFCNT_inc(sv_val), 0 );

You need that. The hash assumes that it is being given the reference you
pass it. But without the SvREFCNT_inc there is only one reference to sv_val,
and the other hash (also) thinks that it owns it.

You were probably also leaking memory even when you didn't have this.


> Now everything works, but I'm getting memory leaks.  I've also tried to clone 
> sv_val using newSVsv() but with the same results. I'm not sure what I'm doing 
> wrong.

I've had a look, and I'm not sure either.
I'm about to head off to YAPC::EU, so I'm not going to have another chance
to look until next week. Hopefully someone else will solve it before then.

Nicholas Clark

Reply via email to