3 ms·
There is a funny version of this: Caller provides memory and function fails if there is to little memory, but writes the the required (variable) amount of memo
by dathinab 4y ago
There is a funny version of this:
Caller provides memory and function fails if there is to little memory, but writes the the required (variable) amount of memory to an `out length` pointer.
Effectively leading to a common pattern of:
1. call function with empty buffer (or buffer or arbitrary size)
2. allocate buffer
3. call function again with properly sized buffer
4. add a loop if between 1 & 3 the required buffer size can change
its fascinating how well it works for some of it's common use cases and how subtle but badly broken it can be for other use cases :=)
- userbinator 4y agoThat's classic "Microsoft style" and I've always hated APIs like that because they add unnecessary complexity to the code of all their callers.
- koyote 4y agoI once had the pleasure of using the Microsoft C API for creating an HMAC: https://docs.microsoft.com/en-us/windows/win32/seccrypto/example-c-program--creating-an-hmac https://docs.microsoft.com/en-us/windows/win32/seccrypto/exa... They managed to mix both patterns into a ghastly 9 function call! The example above speaks for itself but I kind of see the "we provide you with memory you need to call 'FreeX' on" and the "call the function twice, once to find out how much memory you need to allocate" patterns to be equally annoying to use.
- gnubison 4y agoIt’s nice if you would prefer to use a custom allocator, or put small buffers on the stack. But yeah, it is more annoying to use.
- tinus_hn 4y agoYou can’t just dump ‘small’ buffers on the stack in security sensitive code; you never know how big ‘small’ can get and you have to define what happens if it’s too big anyway.
- pjmlp 4y agoYeah, but that is what allows Windows to keep its ABI, while extending some struct across Windows versions. Callers allocate the right size no matter what OS version, and can only see the fields exposed on the version they were built for.