Why, given that SV *a is created in the Perl code and is not going out of scope, do I have to increment the ref count when I return it to Perl in order to avoid Attempt to free unreferenced scalar: SV 0x182445c, Perl interpreter: 0x2240d4.?

In your sub:
SV* test( SV *a, SV *b ) {
you get copy of scalars and not references to them. Not C but Perl will create a copy for you and pass to your subroutine. So you will see reference count in your sub equals to 1 even if you make some references to your scalar before calling your sub.
Insert couple of print statements to see your SVs parameters.

You make quite inconsistent thing in your C subroutine, at the very first step. You either replace SV *a with a new SV or do not, based on its constant-ness. Its a hole for scalar leaks. And may be your comment "// Why do I need to increment the ref count?" will go away. What will happen if you do not do "REFCNT_inc" exactly? Will the subroutine work for non-constant scalars?

Why not write following way:

SV* test( SV *a, SV *b ) { SV *c = newSVsv(a); sv_catsv(c,b); return c; }
As a side note, Inline::C is perfect for trivial cases, but when dealing with refernce counts and stuff you'll get another layer of hidden mechanics, so you'll have things under better control if you'll go to XS directly.
IOW Inline::C helps a great deal at the beginning, but it will add uncertainity after complexity grows a little.

In reply to Re: XS/Inline::C concat *any* two SVs. by vkon
in thread XS/Inline::C concat *any* two SVs. by BrowserUk

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.