malloc() in microcontrollers is generally considered a "bad thing". But, if you absolutely need it then you'll want to find a third party version.
If you're lucky, the code you're porting may not rely on reusing blocks of memory. If this is the case, you can write a simple allocator which returns a pointer into a RAM buffer, then advances the pointer by the requested block size.
I've successfully used this approach before in porting PC libraries to microcontrollers.
Below, you'd setup the allocator with
my_malloc_init() and allocate memory with
my_free() is there to satisfy the dependency but won't actually do anything. Eventually you'll run out of space, of course.
To make this work, you'll need to measure the worst-case memory requirement of your code (do this on a PC if possible) then set up
HEAP_SIZE accordingly. Before entering the part of your library requiring dynamic memory, call
my_malloc_init(). Before re-use, make sure nothing still points at
heap_ptr = heap;
void *my_malloc(size_t len)
uint8_t *p = heap_ptr;
heap_ptr += len;
if (heap_ptr >= heap + HEAP_SIZE)
// do nothing
(note: in the real world, you might need to consider pointer alignment, ie. rounding up
heap_ptr by 2 or 4 bytes)
Another option is to use a simpler allocation structure than
malloc() usually provides, like a FreeList, though this may not allow you to allocate variable sized blocks.