note
BrowserUk
<p>Ignoring the typo (<c>newSvif</c>), 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.
<p>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: <c>my $var = someCfunc();</c>) 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.
<p>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:<code>
#! 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 17.
Use of uninitialized value in join or string at C:\test\junk.pl line 17.
</code>
<p>Run the above code in a large loop to see the memory leak.
<P>Fixing those two errors and the program now returns the anon array of values and stops leaking:<code>
#! 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
...
</code>
<blockquote><i>I did look at perlapi, and perlxstut, </i></blockquote>
<p>For question 2, the documentation you need, and examples are in [perlcall].
<div class="pmsig"><div class="pmsig-171588">
<hr />
<font size=1 >
<div>With the rise and rise of 'Social' network sites: 'Computers are making people easier to use everyday'</div>
<div>Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.</div>
<div>"Science is about questioning the status quo. Questioning authority". </div>
<div>In the absence of evidence, opinion is indistinguishable from prejudice.</div>
</font>
</div></div>
934455
934455