Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Perl XS: Memory management

Tags:

c

perl

xs

I am absolutely new to Perl XS.

My simple testfunction gets a string and appends something. In Perl is is a scalar-string in and one out.

In the function I have a malloc. Whats the correct way to free the mem?

SV *foo (str)
   SV *str
CODE:
    unsigned char *strbuf;
    size_t strlen;
    strbuf = (unsigned char *) SvPV (str, strlen);

    int n = strlen + 10;
    unsigned char *buf = malloc (n);    

    strncpy (buf, strbuf, strlen);
    strncat (buf, "0123456789", 10);

    RETVAL = newSVpv (buf, n);
OUTPUT:
    RETVAL

thanks! Chris

like image 577
chris01 Avatar asked Jul 12 '16 20:07

chris01


1 Answers

newSVpv creates an internal copy of the string, so you can simply free the memory by calling free after assigning to RETVAL.

like image 88
nwellnhof Avatar answered Nov 03 '22 06:11

nwellnhof