in reply to When to (and not to) use sv_2mortal()
Ignoring the typo (newSvif), the sub as posted doesn't work -- the reference returned to Perl refers to an empty array -- and leaks memory -- the reference returned is never garbage collected.
You should (only) use sv_2mortal() on scalars that are placed on the stack. The reason is that the way the perl code gets access to these scalars is when they are copied (by assignment: my $var = someCfunc();) when the sub is called. As soon as that assignment is done, the SV placed on the stack is no longer needed or accessible, so unless you drop its refcount ("make it mortal") it will persist until the program ends. This is where your posted code is leaking, because you are not making the AV* you push onto the stack mortal. Call the function in a loop and your memory will grow and grow.
Conversely, you are making the SVs you are pushing into the (anonymous) AV mortal. As the are never copied by the call/return process -- only the ref is copied, not the referent -- by the time you try to dereference the copy of the AV* returned in order to access its contents, they have been garbage collected and the anonymous array is empty:
#! perl -slw use strict; use Inline C => Config => BUILD_NOISY => 1; use Inline C => <<'END_C', NAME => 'junk', CLEAN_AFTER_BUILD => 0; AV* return_an_array() { AV* av; av = newAV(); av_push( av, sv_2mortal( newSViv( 7 ) ) ); av_push( av, sv_2mortal( newSViv( 42 ) ) ); return av; } END_C my $ref = return_an_array(); print "@{ $ref }"; __END__ C:\test>junk Use of uninitialized value in join or string at C:\test\junk.pl line 1 +7. Use of uninitialized value in join or string at C:\test\junk.pl line 1 +7.
Run the above code in a large loop to see the memory leak.
Fixing those two errors and the program now returns the anon array of values and stops leaking:
#! perl -slw use strict; use Inline C => Config => BUILD_NOISY => 1; use Inline C => <<'END_C', NAME => 'junk', CLEAN_AFTER_BUILD => 0; AV* return_an_array() { AV* av; av = newAV(); av_push( av, newSViv( 7 ) ); av_push( av, newSViv( 42 ) ); return sv_2mortal( av ); } END_C for ( 1 .. 1e8 ) { my $ref = return_an_array(); print "@{ $ref }"; } __END__ C:\test>junk 7 42 7 42 7 42 7 42 7 42 ...
I did look at perlapi, and perlxstut,
For question 2, the documentation you need, and examples are in perlcall.
|
---|
Replies are listed 'Best First'. | |
---|---|
Re^2: When to (and not to) use sv_2mortal()
by davido (Cardinal) on Oct 28, 2011 at 21:55 UTC | |
by BrowserUk (Patriarch) on Oct 28, 2011 at 22:23 UTC | |
by davido (Cardinal) on Oct 28, 2011 at 22:40 UTC | |
by BrowserUk (Patriarch) on Oct 28, 2011 at 22:56 UTC | |
Re^2: When to (and not to) use sv_2mortal()
by patcat88 (Deacon) on Oct 29, 2011 at 15:06 UTC | |
by BrowserUk (Patriarch) on Oct 30, 2011 at 01:10 UTC | |
by patcat88 (Deacon) on Nov 02, 2011 at 00:00 UTC | |
by BrowserUk (Patriarch) on Nov 02, 2011 at 05:57 UTC |