TransWikia.com

Understanding heap fragmentation

Arduino Asked on December 19, 2021

I finally understand why people do not allocate memory when it comes to micro-controllers. The reason is because as you allocate different objects on the heap of various sizes and then you delete them you end up with holes. This is called heap fragmentation. Anyways I know what is heap fragmentation. I just want to know how it works. So that I know when I can use the new keyword to allocate memory and when not..

(1) To make things simple consider this example. Lets say my heap looks like this. The bottom numbers represent the addresses. In a real example I will be allocating structs with larger sizes but lets use bytes to make things simple.

0    0    0    0    0    0    0    0    0    0    
1    2    3    4    5    6    7    8    9    10

(2) I allocate a char with value 123 in memory. Now my heap looks like this

1    0   123   0    0    0    0    0    0    0    
1    2    3    4    5    6    7    8    9    10

the first 2 bytes 1 0 store the size of the data being allocated followed by the byte 123 that has the actual value.

(3) I allocate another char with value 111 in memory. Now my heap looks like this

1    0   123   1    0   111   0    0    0    0    
1    2    3    4    5    6    7    8    9    10

(4) I delete the first object created on step 2 with value 123. It now looks like:

0    0    0    1    0   111   0    0    0    0    
1    2    3    4    5    6    7    8    9    10

I now have a hole at the beginning (heap fragmentation)

Now my question is if I where to allocate another byte say 222 will it be allocated on the beginning like this?

1    0   222   1    0   111   0    0    0    0    
1    2    3    4    5    6    7    8    9    10

Or will it be allocated at the end like this?

0    0    0    1    0   111   1    0   222   0    
1    2    3    4    5    6    7    8    9    10

If arduino is smart enough to place that object at the beginning, then I will no be that afraid of using the new keyword as long as I am allocating objects of small sizes and never allocating to many of them.

Reason why I am asking this question is because I have a class Queue that I use in c++. Whenever I add an item to that queue it allocates the objects that I create. The objects that I pass to that queue are 10 bytes. The queue size is never larger that size 30. Will it be safe if that queue is constantly allocating (enqueing) and deleting (dequeing) items?


Edit

Sorry for the question I guess I asked this question when I should had done more research. Thanks to your comments and my previous question I now know that this only occurs when allocating memory of different sizes.

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP