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:
@data : Pointer(SomeType)
@data = LibYourLib.getifaddrs
@data = Pointer(SomeType).null
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:
if not_nil_data = @data
Thank you for your response.
I got it.
I will try to implement freeing those objects.
You should probably also use out to simplify the code, and checking a
null pointer is not needed because
-1 on failure.