Beefy Boxes and Bandwidth Generously Provided by pair Networks
The stupid question is the question not asked
 
PerlMonks  

Re: What difference between malloc and Newx, how attach a C string to SV directly?

by Corion (Patriarch)
on Sep 29, 2019 at 07:41 UTC ( [id://11106828]=note: print w/replies, xml ) Need Help??


in reply to What difference between malloc and Newx, how attach a C string to SV directly?

Newx wraps malloc.

perlguts shows the following snippet to attach a buffer to an SV:

Newx(buf, somesize+1, char); /* ... fill in buf ... */ buf[somesize] = '\0'; sv_usepvn_flags(sv, buf, somesize, SV_SMAGIC | SV_HAS_TRAILING_ +NUL); /* buf now belongs to perl, don't release it */

Note how Perl considers the buffer to belong to Perl now.

If you want to completely manage the lifetime of the buffer yourself (static data, irrespective of SVs that point to it), I think there is a way to have a PV be a pointer to memory that is not free'd by Perl, but none of my reading of the documentation turns up how that works, or an example of it.

Replies are listed 'Best First'.
Re^2: What difference between malloc and Newx, how attach a C string to SV directly?
by xiaoyafeng (Deacon) on Sep 29, 2019 at 08:08 UTC

    Note how Perl considers the buffer to belong to Perl now.

    yeah, if buf produced from malloc which means it's not belong to perl, program will throw a segment fault error. I guess Newx maybe not just a simple wrap of malloc, it does a register pointer address to perl when which assure perl could free it safely.

    I think there is a way to have a PV be a pointer to memory that is not free'd by Perl, but...

    yes, I think it too, that's why I post question on perlmonks. ;)




    I am trying to improve my English skills, if you see a mistake please feel free to reply or /msg me a correction

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://11106828]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others taking refuge in the Monastery: (6)
As of 2024-04-24 09:06 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found