Bug 1:

You are including the NUL in the buffer, and you are falsely claiming there is a trailing NUL after the buffer.

sv_usepvn_flags(x, dx, 8, SV_HAS_TRAILING_NUL);
should be
sv_usepvn_flags(x, dx, 7, SV_HAS_TRAILING_NUL);
and it should be written as
sv_usepvn_flags(x, dx, strlen(dx), SV_HAS_TRAILING_NUL);

Bug 2:

The buffer can't be modified, but you offer no protection. For example, $x =~ s/./a/s; will result in undefined behaviour (which fortunately segfaults on my machine).

Add the following:

SvREADONLY_on(x);

I found you can't enlarge the SV containing C string by using .=, no any error throw though.

I already mentioned that. Or rather, I mentioned that it causes the buffer to get replaced with a new one that contains a copy.

Before $x .= "a";:

SV = PV(0x3e1a1785e0) at 0x3e1a197528 REFCNT = 1 FLAGS = (POK,pPOK) PV = 0x35260c8bbd5 "dddddd" <-- Pointer into C static storage CUR = 6 LEN = 0 <-- Doesn't belong to Perl.

After $x .= "a";:

SV = PV(0x3e1a1785e0) at 0x3e1a197528 REFCNT = 1 FLAGS = (POK,pPOK) PV = 0x3e1a19fe50 "dddddda"\0 <-- New buffer (copy + "a") CUR = 7 LEN = 17 <-- Belongs to Perl.

However, SvREADONLY_on(x) will prevent this. So if you want to allow this, you'll need to remove the READONLY flag, which means you'll need to make a copy of the constant string.


In reply to Re^2: What difference between malloc and Newx, how attach a C string to SV directly? by ikegami
in thread What difference between malloc and Newx, how attach a C string to SV directly? by xiaoyafeng

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.