On Wed, Jul 30, 2008 at 12:16 PM, Sisyphus <[EMAIL PROTECTED]> wrote:
>
> Better to allocate/free memory using New/Safefree instead of malloc/free.
Why? That memory is never being seen by Perl. Why not leave it as-is,
if you're just going to free it anyway?
> use warnings;
> #use Devel::Peek;
>
> use Inline C => <<'EOC';
>
> SV * foo(char *x) {
> SV * ret;
> char * str2ret;
> STRLEN len = strlen(x);
>
> printf("%d\n", len);
>
> New(0, str2ret, len * 2, char);
> if(str2ret == NULL) croak("Failed to allocate memory for str2ret");
>
> // Do stuff
>
> ret = newSVpv(str2ret, len * 2);
>
> Safefree(str2ret);
> return ret;
> }
>
> EOC
This is untested, but wouldn't it be easier to just do:
SV* work(char* inString)
{
SV* ret;
char *stringToReturn = (char *)malloc(2*sizeof(inString)); // I
think you meant strlen? +1?
while(*inString){
// do some work on stringToReturn
inString++;
}
ret = newSVpv(stringToReturn, 0); // or
newSVpvn(stringToReturn, 2 * strlen(inString)) or whatever
free(stringToReturn);
return ret;
}