arcage
1
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?
scott
2
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
arcage
3
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