3 ms·
Avoid as much as you can the C standard lib allocator, go directly to mmap system call with your own allocator if you know you won't use CPU without a MMU. If
by sylware 2y ago
Avoid as much as you can the C standard lib allocator, go directly to mmap system call with your own allocator if you know you won't use CPU without a MMU.
If you write a library, let the user code install its own allocator.
- jeffbee 2y ago"malloc" is a weakly-bound symbol that can be overridden, on every system I've used. I don't know if some standard defines it to be weak. Anyway the point is that malloc is not necessarily a call to the C standard library function. It can be anything.
- sylware 2y ago"weakly-bound symbol" implies your a using a complex runtime library/binary format (like ELF). A portable and clean design for a library is to allow to override the internal allocator via the API (often part of the init function call). Look at vulkan3D which does many things right and doing this very part right. On the other side, you have some parts of the ALSA lib API which still requires to use the C lib free (may be obsolete though).
- kevin_thibedeau 2y agoThe linker doesn't try to resolve symbols it's already seen while static linking. This doesn't require a weak linkage flag for overriding system library functions since libc is linked at the end by default when static linking or at runtime when dynamic.
- pjmlp 2y agoSure, if one doesn't care about portable code.
- the-smug-c-one 2y agoWhat modern OS doesn't have the equivalent of mmap? Just som #ifdefs. I didn't know I'd ever hear "use malloc, because it's portable". sylware is pretty much right anyway. Try to avoid malloc, or write smaller allocators on top of malloc.
- pjmlp 2y agoWhy bother with some #ifdefs when the ISO C standard library already does the job?
- the-smug-c-one 2y agoBecause you're probably writing a much larger program so some ifdefs aren't a big deal :-).
- keyle 2y agoThis is a silly argument because at the end of the day, once you make your code portable, you've now duplicated 99% of malloc and free, and you've left a mess for the team or next guy to maintain on top of everything else. You've successfully lowered the abstraction floor which is already pretty low in C.
- sylware 2y agowhat?? The whole point is to create independence, then create "real-life" alternatives. I don't understand your point.
- commandlinefan 2y ago> go directly to mmap system call TFA said that, too... IIRC (and based on a quick googling), mmap is for memory-mapping files into the virtual address space. I thought sbrk() was used for low-level adjustment of available memory and malloc was responsible for managing an allocation handed to it by the sbrk() call. Or has that fallen out of fashion since I last did low-level C programming?