Skip to main content


This is something you are probably NOT supposed to be doing with #perl but consider my innocent looking C code found in an Inline::C region (which will be discussed in my talk).
If my understanding of the API is correct, then this macro allocates a buffer of known size in bytes and puts the buffer under the #Perl garbage collector. One only needs an entry point from Perl to #C and one just enhanced their #Clang code with a garbage collector
for safe memory management.
@Perl
in reply to Christos Argyropoulos MD, PhD

I don't see any garbage collecting. If you don't register sv for cleanup later, it'll probably just leak.
(Also, why not just SV *sv = newSVpvn(buf, buffer_size);?)
in reply to Füsilier Breitlinger

@barubary
Regarding the allocation sequence (comments all based on my understanding of perlguts)
1) newSVpvn(const char*, STRLEN) -> allocates STRLEN+1 (for C's 'terminal \0') while
2) Newxz gives one the size they want (
3) sv_usepvn_flags can then be applied and the buffer now belongs to perl (see screenshot) through the SV that was just created to hold it
in reply to Christos Argyropoulos MD, PhD

SV_HAS_TRAILING_NUL promises that buf[buffer_size] == '\0' (i.e. buf has actually buffer_size+1 elements). In your code, that's not the case, so that's not a valid PV string buffer. See perldoc.perl.org/perlapi#sv_us…:

And if flags & SV_HAS_TRAILING_NUL is true, then ptr[len] must be NUL, and the realloc will be skipped (i.e., the buffer is actually at least 1 byte longer than len, and already meets the requirements for storing in SvPVX).


(Also, SV_MAGIC seems weird for a newly allocated SV, which is guaranteed to not have magic.)

This entry was edited (10 months ago)
in reply to Füsilier Breitlinger

@barubary
Hm, I am not using these SV as strings, I am allocating a space of sufficient size to hold a C struct, and lie to perl that it has a terminal zero to avoid copying the buffer to a new area in memory and have its size extended by 1 to hold the terminal '\0'

It is easy to see that memory does not leak by creating an example in which the SV is mortalized. Code in alt text. Upon execution there is a warning about the freeing of the area allocated in C when the program terminates.

in reply to Christos Argyropoulos MD, PhD

That's not how the API is intended to work. And on a debugging Perl, that will just crash due to an assertion failure: github.com/Perl/perl5/blob/ee4…
in reply to Füsilier Breitlinger

Agreed that the SV_MAGIC is weird, but look at the examples
perldoc.perl.org/perlguts#Work…

Every single one of the sets the MAGIC flag when working in C with buffers.

There is probably some undocumented MAGIC that requires the MAGIC to be set.

This entry was edited (10 months ago)