|
|
|
|
|
by thxg
1409 days ago
|
|
One slight variation on the getaddrinfo()/freeaddrinfo() approach is what (among many others) GMP [1] and its derivatives do: For every struct or custom type, you systematically get void type_init(type *t, [...]);
void type_clear(type *t, [...]);
This is essentially explicit constructors and destructors in C, and one can legitimately argue that it is clunky, verbose and error-prone.However, if we are constrained to a C API, it does have one important practical quality in my experience: Because it is always the same, it eases the mental load on both the API's user and the API's implementer, especially if there are many such types involved. [1] See e.g. https://gmplib.org/manual/Initializing-Integers |
|
Clunky and verbose, yes, error-prone no. The APIs that do that are generally much more clear about ownership, and thus much easier, IMO, to write correct code for. Much worse is the API that returns you a pointer with no obvious mechanism to free it. Is it tied to the lifetime of an input to the function that returned it? Is it a global and this API is completely thread-unsafe? Am I leaking memory?