diotalevi has asked for the wisdom of the Perl Monks concerning the following question:

I wrote the following Inline::C function to work through what it takes to create a scalar successfully. The string portion of the scalar is not null and I thought it should be. Am I doing this wrong or am I expected to zero it out manually?

$ perl new.pl SV = PV(0x7460) at 0x35cb4 REFCNT = 1 FLAGS = (TEMP) PV = 0x6330 " \0w.pl\0\0\0\0"\0 CUR = 10 LEN = 11
use Devel::Peek; use Inline C=> 'DATA'; Dump(foo( 10 )); sub vis { map { join '', map sprintf("\\%o", ord), split // } @_ } __DATA__ __C__ SV* foo(int nr) { SV* out = NEWSV(535,nr); SvUPGRADE(out,SVt_PV); SvCUR_set(out,nr); return (out); }

Replies are listed 'Best First'.
Re: NEWSV'd scalar isn't initially empty?
by diotalevi (Canon) on Aug 04, 2003 at 16:09 UTC

    Ah. On reading the perl source I think I should have written this thusly. This leaves off the upgrade and grow (that's apparently handled within NEWSV when len > 0) and since NEWSV uses New() instead of Newz(), I had to follow up with an explicit Zero() on the PV. So... is *this* right? I added a SvPOK_only() call as well because without that the only flag on it was TEMP. If I do my $foo = foo(); Dump($foo) the REFCNT is one - is that right and am I supposed to mortalize the scalar I'm returning here?

    SV* foo(int nr) { SV* out = NEWSV(535,nr); SvPOK_only(out); Zero(SvPVX(out), nr, char); SvCUR_set(out,nr); return (out); }
      Well - the REFCNT of $foo has to be one - it is a copy of the SV * returned from foo(). I am pretty sure that you should add sv_2mortal(out) to your function to avoid leaking the SV.

      Michael