logoalt Hacker News

irishcoffee • yesterday at 8:35 PM • 1 reply • view on HN

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.


Replies

jz391 • yesterday at 10:53 PM

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.

➕ show 1 reply