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
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |