Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to handle heap memory fragmentation in AVR/Arduino microcontrollers?

I've been searching for a few days now without any luck.

Heap memory fragmentation is a result of using malloc() and free() heavily in microcontrollers/Arduino.

If using them is unavoidable, how can I defragment the heap every now and then to make sure that the next malloc() call will find contiguous memory to allocate?

like image 328
Islam Mustafa Avatar asked Feb 10 '23 13:02

Islam Mustafa


1 Answers

Create a pool of fixed-size memory chunks. When you need any amount of memory, allocate one of the chunks from the pool and use the portion you need. When you're done with it, return the chunk to the pool. The pool will never fragment because the chunks are always the same size. And if any chunks are available then they're always the right size. Sometimes you'll need only a couple bytes and for a second you'll think that you're being wasteful for tying up an entire chunck. But then you'll remember that you're avoiding memory fragmentation and you'll feel better about it.

If the size of your allocations vary greatly then one fixed-size memory pool might really be too wasteful. Then you can make two or three fixed-size memory pools for small, medium, and large chunks. But make sure you return the chunks to the same pool that you obtained them from.

Use a queue or a linked list to organize the chunks in the pool. The chunks are removed from the queue/list when they're allocated. And they're returned to the queue/list when they're freed.

like image 122
kkrambo Avatar answered Apr 27 '23 17:04

kkrambo