perl.inline
[Top] [All Lists]

Re: Allocating a char* and returning to Perl from a C function

Subject: Re: Allocating a char* and returning to Perl from a C function
From: sisyphus1@xxxxxxxxxxxxxxx (Sisyphus)
Date: Thu, 31 Jul 2008 11:03:38 +1000
Newsgroups: perl.inline



----- Original Message ----- From: "Steve Fink" <sphink@xxxxxxxxx>
To: "Sisyphus" <sisyphus1@xxxxxxxxxxxxxxx>
Cc: "Paulo Filipe Andrade" <pfca@xxxxxxxxxxxxxxx>; <inline@xxxxxxxx>
Sent: Thursday, July 31, 2008 8:44 AM
Subject: Re: Allocating a char* and returning to Perl from a C function


On Wed, Jul 30, 2008 at 12:16 PM, Sisyphus <sisyphus1@xxxxxxxxxxxxxxx> 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?

I've no objection to that. It's just that New/Safefree is the general recommendation, and it has never given me any trouble. By the same token, on the few occasions where I've used malloc/free, I've had no trouble with that either. (I *have* struck awful trouble with calloc.)


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);

You definitely *don't* want to do that if stringToReturn can have embedded null chars.

// or
newSVpvn(stringToReturn, 2 * strlen(inString))

No problems with that. (And according to perlapi, newSVpvn is more efficient than newSVpv.)

Cheers,
Rob


<Prev in Thread] Current Thread [Next in Thread>