Should I release HV * created using newHV?

If I write some XS code with a hash that I never expect to return to perl, do I need to free it? If so, how?

The closest I came up with hv_undef, but this only clears the contents of the hash, and not the hash itself, from what I understand.

HV* hash = newHV(); ... use the hash ... hv_undef(hash); 
+8
memory-leaks perl perl-xs
source share
2 answers

newHV (e.g. newSV , newAV , etc.) sets the reference count of the newly created value to 1. To free it, you just need to reduce it to 0 . There is no special function for HV, so just use SvREFCNT_dec :

 HV* hash = newHV(); /* * use the hash */ SvREFCNT_dec((SV *) hash); 
+10
source share

newHV returns an HV with a reference number (refcnt) of one, which means that your code is held on an HV . When you are done with this HV , you should free it by decreasing its refcnt. There are three general ways to do this.

  • Done here and now.

     SvREFCNT_dec((SV*)hv); // hv is no longer safe to use here. 

    AV and HV are subclasses of SV .

  • It is executed with it after the caller has the opportunity to refer to it. (Actually, this does not apply to hashes.)

     return sv_2mortal(sv); 
  • Transfer ownership.

     rv = newRV_noinc((SV*)hv); 

    This is short for

     rv = newRV((SV*)hv); SvREFCNT_dec((SV*)hv); 

    Note that you should also release the rv trick when you are done with it, so you will often see the following:

     return sv_2mortal(newRV_noinc((SV*)hv)); 
+7
source share

All Articles