Should I free the objects made by C functions?

I have used getifaddrs() function of libc from my crystal code.

And, I found following line in the getifaddrs(3) man page

The data returned by getifaddrs () is dynamically allocated and should be freed using freeifaddrs () when no longer needed.

In these case, should I manually free the objects that dynamically allocated by C functions?

Or, crystal GC will automatically collect them?

You will need to manually free the resource as you would in C. You can wrap the object in a class to get the GC to free it for you:

class IfAddrs
  @data : Pointer(SomeType)
  def initialize
    @data = LibYourLib.getifaddrs
     # OR?
    @data = Pointer(SomeType).null
    LibYourLib.getifaddrs @data
  end
  def finalize
    LibYourLib.freeifaddrs @obj
  end
end

You should also bear in mind that the Pointer type is not null-safe and you should be checking if @data is null before every use:

class IfAddrs
  ....
  def data?
    @data
  end
  def data
    if not_nil_data = @data
      return not_nil_data
    else
      raise NullPointerException.new
    end
  end
  ...
end
2 Likes

Thank you for your response.

I got it.

I will try to implement freeing those objects.

1 Like

You should probably also use out to simplify the code, and checking a null pointer is not needed because getifaddrs returns -1 on failure.

2 Likes

Thanks for all.

I updated my repo.

  1. By using freeifaddrs() function, I confirmed that memory usage was not increased by multiple getifaddrs() calls.

  2. I added error check(return value check) when calling getifaddrs().

  3. I replaced some variable definitions to using out keyword.

2 Likes