Hi all, please consider this example from FFI::Platypus:

#include <string.h> #include <stdlib.h> const char * string_reverse(const char *input) { static char *output = NULL; int i, len; if(output != NULL) free(output); if(input == NULL) return NULL; len = strlen(input); output = malloc(len+1); for(i=0; input[i]; i++) output[len-i-1] = input[i]; output[len] = '\0'; return output; }
use FFI::Platypus 2.00; my $ffi = FFI::Platypus->new( api => 2, lib => './string_reverse.so', ); $ffi->attach( string_reverse => ['string'] => 'string' ); print string_reverse("\nHello world"); string_reverse(undef);

Note the second call of string_reverse. From ibidem:

"At the end of the program we call reverse_string with undef, which gets translated to C as NULL. This allows it to free the output buffer so that the memory will not leak."

A smart aleck might jump to the conclusion to replace malloc with GC_MALLOC as described here.

Is this recommended or will it cause problems in the future not yet imaginable now?

Thanks for any hint and best regards, Karl

P.S.: See also Boehm–Demers–Weiser Garbage Collector

Update: Thank you all for the kind and very informative responses. I now consider this a research project for the future. So far I don't even know if the mentioned library compiles on the Mac. I will report back.

«The Crux of the Biscuit is the Apostrophe»


In reply to FFI::Platypus: Replace malloc with GC_MALLOC? by karlgoethebier

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.