3 ms·
Of course this very paradigm, combined with the fact that C doesn’t have a proper pointer-and-length type, led to `gets` and around n million other security dis
by Sharlin 4y ago
Of course this very paradigm, combined with the fact that C doesn’t have a proper pointer-and-length type, led to `gets` and around n million other security disasters when bad APIs would just take a pointer without a length and assume there’s "enough" space…
Anyway, the whole "caller allocates" concept doesn’t work too well in the particular case of `gethostbyname`, which as the author mentions, is a complex struct containing several pointers and double pointers, with a potentially unlimited number of different-length allocations one would have to make!
- usefulcat 4y agoFor things that create complex in-memory data structures, an alternative is to use callbacks instead. Users can still create such data structures if they want to but at least that way heap allocations are optional.
- ectopod 4y agoCaller allocates works fine. gethostbyname would effectively serialize all of the result data into the supplied buffer. All of the pointers in the struct would be internal to the buffer (they point to the serialized data) so they don't need to be freed.
- Sharlin 4y agoYeah, but it would be nigh impossible to guess in advance how much space would be needed. The "solution" where the caller tries again with exponentially increasing buffer sizes really doesn't fit my concept of a good API. And if the callee calculates and returns how much memory it would need, then the caller needs to heap allocate to make use of that information (or resort to nonstandard functions like `alloca`). Honestly best just to return a pointer to a dealloc function (which could simply be `free` if the struct and the data it points to are indeed allocated as a contiguous block of memory).