Remix.run Logo
▲ irishcoffee 3 hours ago

Whenever I write I library I don't allocate memory. If memory needs to be allocated, the program calling into the library allocates memory and passes a pointer (or reference I suppose) into the library call.

Clearly this can't be enforced, but I've always found it bad practice to allocate memory inside a library.

▲jz391 an hour ago | parent [-]

How to you manage the API when caller doesn't know the right size to allocate? I mean you could pass an allocator object (ala zig/C++ stdlib etc), though I'm not sure I like the extra arg on functions... I guess a quasi-global-variable approach (e.g. a "context" object, passed to all functions, which can hold an allocator, or equivalently implicit arguments in a functional language) would be one way to achieve that without the "noise" of explicit allocators passed everywhere.

▲okanat 31 minutes ago | parent [-]

You can also design a "dual-pass" API. Basically you have an API call to estimate or calculate the memory usage needed and then another parameter / API call to actually do the operation.

For example the WideCharToMultiByte [1] function of Win32 handles UTF-16 to UTF-8 conversion. If you pass your destination pointer as NULL, then it purely calculates the number of bytes you'll need in your buffer. Then the main program actually allocates the memory and calls it again with the populated destination pointer.

[1]: https://learn.microsoft.com/en-us/windows/win32/api/stringap...