Search code examples
rubyffi

In Ruby FFI when I return a dynamically allocated string should I free it?


I have the following function in C

char* strfunc()
{
   char* ch=calloc(100,1);
   strcpy(ch,"hello");
   return ch;
}

Then in ruby I have

module XYZ
   extend FFI::Library
   ffi_lib "mylib.so"
   attach_function :strfunc, [] , :string
end

Should I import free to free memory allocated to the string returned or will Ruby GC do that for me?


Solution

  • Nor FFI, nor ruby GC will free it automatically, because, they does not know it's malloc'd and not just some static memory.

    You should free it manually with libc's free() call. Please, reference to this ticket https://github.com/ffi/ffi/issues/467 for examples.