in reply to XS-ive Mortality. (or when to use sv_2mortal())
The problem with this approach is what happens if something gets wrong inside do_something() and it calls croak. It longjmps to someplace in the perl core over your clean up code and you start leaking memory.SV *tmp = newSVsv(foo); do_something(tmp); SvREFCNT_dec(tmp);
To solve that, you can use sv_2mortal, it remembers the SV so that, when control leaves the XS in any way, SvREFCNT_dec gets automatically called on it. The previous code is best written as:
SV *tmp = sv_2mortal(newSVsv(foo)); do_something(tmp); /* no clean up code required here */
In reply to your question, when is it necessary to call sv_2 mortal?, the answer is always, unless you want the SV to survive the XS call (for instance if you are saving a reference to it inside a C struct or global variable).
If you want to store it inside a perl container (AV or HV), the safe way to do it is:
... av can have some magic attached (if it is a tied array for instance) and call croak from inside the av_store, that's why you need to mortalize the SV first and later increment the ref count if the call to av_store doesn't fail.SV *tmp = sv_2mortal(newSVsv(foo)); if (av_store(av, ix, tmp)) SvREFCNT_inc(tmp);
Anyway, in the API documentation (perlapi) you will find which functions change the reference count of SVs (or AVs, HVs, etc). It could be summarized as: no function touchs the ref count unless it is a constructor (which sets ref count to 1) or it is a ref count manipulation function (SvREFCNT_inc, SvREFCNT_dec, sv_2mortal). Update functions that manipulate containers (AVs, HVs or RVs) as a whole, update the refcounts of the contained elements as required, for instance, if an AV is cleared, its elements ref counts are decremented.
You can also control when mortalized variables are freed, with the SAVETMPS and FREETMPS macros. For instance, if you are creating SVs inside a loop, and you mortalize them, they are not going to be freed until the sub returns, and if it is a big loop it is going to require a lot of memory. With those macros you can free mortalized SVs created inside the loop in every iteration so the same memory is used by your temps over and over. See perlcall for more details.
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: XS-ive Mortality. (or when to use sv_2mortal())
by BrowserUk (Patriarch) on Mar 13, 2006 at 21:43 UTC |