----- Original Message ----- From: "Steve Fink" <[EMAIL PROTECTED]>
To: "Sisyphus" <[EMAIL PROTECTED]>
Cc: "Paulo Filipe Andrade" <[EMAIL PROTECTED]>; <inline@perl.org>
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 <[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?

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

Reply via email to