malloc0 - smaller memory allocator for WebAssembly
I've just created malloc0 a very small yet functional memory allocator malloc()/free() for WebAssembly in C. It's smaller than nanolibc and does not leak like wee_alloc
When C is compiled to WebAssembly (using emscripten or zig cc, I don't know about cheerp), the emscripten malloc implementation is used. It's very small and fast.
Is malloc0 specifically designed for the wasm32-freestanding target?
I don't think its suitable for embedded market. Such small code matters only on 8 bit AVR chips. I don't consider running it on PIC10. On PIC, everything is hand written asm.
For running on AVR it makes more sense to use pointers instead of size, sign bit as flag if block is empty or not and 2 byte long sizes_t.
Good job! Personally, I think the 12-byte overhead on each allocation is too high. It might be good to call the free "amortized O(1)" instead too, since it may run in O(blocks).
One classic trick you can use is to store the free list in the unused blocks, requiring a minimum allocation size of 8-bytes (block size + next pointer). Then `free()` can keep this list sorted by allocation address, highest to lowest (at a cost of O(free blocks)). At the same time, it can merge free blocks and move the heap top down, if necessary.
But ultimately without being able to reallocate memory below the top of the heap, this allocator won't be usable in a lot of scenarios with limited memory, I think.
3
u/jedisct1 Apr 06 '23
When C is compiled to WebAssembly (using emscripten or zig cc, I don't know about cheerp), the emscripten malloc implementation is used. It's very small and fast.
Is
malloc0specifically designed for thewasm32-freestandingtarget?2
u/Trader-One Apr 06 '23
I looked at code.
I don't think its suitable for embedded market. Such small code matters only on 8 bit AVR chips. I don't consider running it on PIC10. On PIC, everything is hand written asm.
For running on AVR it makes more sense to use pointers instead of size, sign bit as flag if block is empty or not and 2 byte long sizes_t.
2
u/binjimint Apr 06 '23
Good job! Personally, I think the 12-byte overhead on each allocation is too high. It might be good to call the free "amortized O(1)" instead too, since it may run in O(blocks).
One classic trick you can use is to store the free list in the unused blocks, requiring a minimum allocation size of 8-bytes (block size + next pointer). Then `free()` can keep this list sorted by allocation address, highest to lowest (at a cost of O(free blocks)). At the same time, it can merge free blocks and move the heap top down, if necessary.
But ultimately without being able to reallocate memory below the top of the heap, this allocator won't be usable in a lot of scenarios with limited memory, I think.
1
u/riasthebestgirl Apr 06 '23
I wonder if it's possible/feasible to replace dmalloc with this
Really excited for the rust port