• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# Heap Memory Management
2
3
4## Basic Concepts<a name="section449414395916"></a>
5
6Memory management module, one of the core modules of the OS, manages the memory resources of the system. Memory management involves memory initialization, allocation, and release. The heap memory management of the OpenHarmony LiteOS-A provides functions such as memory initialization, allocation, and release. While the OS is running, the heap memory management module manages the memory usage of users and the OS by allocating and releasing memory. This helps achieve the optimal memory usage and usage efficiency and minimize memory fragments.
7
8## Working Principles<a name="section465085575911"></a>
9
10Heap memory management, a type of dynamic memory management, allows memory blocks of any size to be allocated from a large contiguous memory \(memory pool or heap memory\) configured in the system based on user demands when memory resources are sufficient. The memory block can be released for further use when not required. Compared with static memory management, dynamic memory management allows memory allocation on demand but causes fragmentation of memory. The heap memory of the OpenHarmony LiteOS-A has optimized the memory space partitioning based on the Two-Level Segregate Fit \(TLSF\) algorithm to achieve higher performance and minimize fragmentation.  [Figure 1](#fig14558185217397)  shows the core algorithm of the heap memory management.
11
12**Figure  1**  Dynamic memory algorithm for small systems<a name="fig14558185217397"></a>
13![](figures/dynamic-memory-algorithm-for-small-systems.png "dynamic-memory-algorithm-for-small-systems")
14
15Multiple free lists are used for management based on the size of the free memory block. The free memory blocks are divided into two parts: \[4, 127\] and \[2<sup>7</sup>, 2<sup>31</sup>\], as indicated by the size class in the above figure.
16
171.  The memory in the range of \[4, 127\] \(lower part in  [Figure 1](#fig14558185217397)\) is equally divided into 31 parts. The size of the memory block corresponding to each part is a multiple of 4 bytes. Each part corresponds to a free list and a bit that indicates whether the free list is empty. The value  **1**  indicates that the free list is not empty. There are 31 bits corresponding to the 31 memory parts in the range of \[4, 127\].
182.  The memory greater than 127 bytes is managed in power of two increments. The size of each range is \[2^n, 2^\(n+1\) -1\], where n is an integer in \[7, 30\]. This range is divided into 24 parts, each of which is further divided into 8 second-level \(L2\) ranges, as shown in Size Class and Size SubClass in the upper part of  [Figure 1](#fig14558185217397). Each L2 range corresponds to a free list and a bit that indicates whether the free list is empty. There are a total of 192 \(24 x 8\) L2 ranges, corresponding to 192 free lists and 192 bits.
19
20For example, insert 40-byte free memory to a free list. The 40-byte free memory corresponds to the 10th free list in the range of \[40, 43\], and the 10th bit indicates the use of the free list. The system inserts the 40-byte free memory to the 10th free list and determines whether to update the bitmap flag. When 40-byte memory is requested, the system obtains the free list corresponding to the memory block of the requested size based on the bitmap flag, and then obtains a free memory node from the free list. If the size of the allocated node is greater than the memory requested, the system splits the node and inserts the remaining node to the free list. If 580-byte free memory needs to be inserted to a free list, the 580-byte free memory corresponds to the 47th \(31 + 2 x 8\) free list in L2 range \[2^9, 2^9+2^6\], and the 47th bit indicates the use of the free list. The system inserts the 580-byte free memory to the 47th free list and determines whether to update the bitmap flag. When 580-byte memory is requested, the system obtains the free list corresponding to the memory block of the requested size based on the bitmap flag, and then obtains a free memory node from the free list. If the size of the allocated node is greater than the memory requested, the system splits the node and inserts the remaining node to the free list. If the corresponding free list is empty, the system checks for a free list meeting the requirements in a larger memory range. In actual application, the system can locate the free list that meets the requirements at a time.
21
22[Figure 2](#fig5395115964114)  shows the memory management structure.
23
24**Figure  2**  Dynamic memory management structure for system systems<a name="fig5395115964114"></a>
25![](figures/dynamic-memory-management-structure-for-system-systems.png "dynamic-memory-management-structure-for-system-systems")
26
27-   Memory pool header
28
29    The memory pool header contains the memory pool information, bitmap flag array, and free list array. The memory pool information includes the start address of the memory pool, total size of the heap memory, and attributes of the memory pool. The bitmap flag array consists of seven 32-bit unsigned integers. Each bit indicates whether the free list is inserted with free memory block nodes. The free list contains information about 223 free memory head nodes. The free memory head node information contains a memory node header and information about the previous and next nodes in the free list.
30
31-   Memory pool nodes
32
33    There are three types of nodes: free node, used node, and end node. Each memory node maintains the size and use flag of the memory node and a pointer to the previous memory node in the memory pool. The free nodes and used nodes have a data area, but the end node has no data area.
34
35
36## Development Guidelines<a name="section577019272015"></a>
37
38### When to Use<a name="section326917198583"></a>
39
40Heap memory management is mainly used to dynamically allocate and manage memory ranges requested by users. Heap memory management is mainly used in scenarios where users need to use memory blocks of different sizes. You can obtain a memory block of a specified size by using a dynamic memory application function of the OS. Once the memory is used up, the memory release function is used to release the occupied memory so that the memory can be reused.
41
42### Available APIs<a name="section1032331584"></a>
43
44The following table describes APIs available for OpenHarmony LiteOS-A heap memory management. For more details about the APIs, see the API reference.
45
46**Table  1**  Heap memory management APIs
47
48<a name="table1415203765610"></a>
49<table><thead align="left"><tr id="row134151837125611"><th class="cellrowborder" valign="top" width="12.85128512851285%" id="mcps1.2.4.1.1"><p id="p16415637105612"><a name="p16415637105612"></a><a name="p16415637105612"></a><strong id="b01375614711"><a name="b01375614711"></a><a name="b01375614711"></a>Function</strong></p>
50</th>
51<th class="cellrowborder" valign="top" width="29.8029802980298%" id="mcps1.2.4.1.2"><p id="p11415163718562"><a name="p11415163718562"></a><a name="p11415163718562"></a><strong id="b132706141086"><a name="b132706141086"></a><a name="b132706141086"></a>API</strong></p>
52</th>
53<th class="cellrowborder" valign="top" width="57.34573457345735%" id="mcps1.2.4.1.3"><p id="p1641533755612"><a name="p1641533755612"></a><a name="p1641533755612"></a>Description</p>
54</th>
55</tr>
56</thead>
57<tbody><tr id="row0415737175610"><td class="cellrowborder" rowspan="2" valign="top" width="12.85128512851285%" headers="mcps1.2.4.1.1 "><p id="p6485848217"><a name="p6485848217"></a><a name="p6485848217"></a>Initializing or deleting a memory pool</p>
58</td>
59<td class="cellrowborder" valign="top" width="29.8029802980298%" headers="mcps1.2.4.1.2 "><p id="p1448511481314"><a name="p1448511481314"></a><a name="p1448511481314"></a>LOS_MemInit</p>
60</td>
61<td class="cellrowborder" valign="top" width="57.34573457345735%" headers="mcps1.2.4.1.3 "><p id="p94857483110"><a name="p94857483110"></a><a name="p94857483110"></a>Initializes a dynamic memory pool of the specified size.</p>
62</td>
63</tr>
64<tr id="row1841519376561"><td class="cellrowborder" valign="top" headers="mcps1.2.4.1.1 "><p id="p20485134810119"><a name="p20485134810119"></a><a name="p20485134810119"></a>LOS_MemDeInit</p>
65</td>
66<td class="cellrowborder" valign="top" headers="mcps1.2.4.1.2 "><p id="p154851348113"><a name="p154851348113"></a><a name="p154851348113"></a>Deletes a memory pool. It is valid only when <strong id="b1987930133815"><a name="b1987930133815"></a><a name="b1987930133815"></a>LOSCFG_MEM_MUL_POOL</strong> is enabled.</p>
67</td>
68</tr>
69<tr id="row1187514443616"><td class="cellrowborder" rowspan="4" valign="top" width="12.85128512851285%" headers="mcps1.2.4.1.1 "><p id="p19661710214"><a name="p19661710214"></a><a name="p19661710214"></a>Allocating or releasing dynamic memory</p>
70</td>
71<td class="cellrowborder" valign="top" width="29.8029802980298%" headers="mcps1.2.4.1.2 "><p id="p66111714213"><a name="p66111714213"></a><a name="p66111714213"></a>LOS_MemAlloc</p>
72</td>
73<td class="cellrowborder" valign="top" width="57.34573457345735%" headers="mcps1.2.4.1.3 "><p id="p4661715214"><a name="p4661715214"></a><a name="p4661715214"></a>Allocates memory of the specified size from the dynamic memory pool.</p>
74</td>
75</tr>
76<tr id="row1745415527441"><td class="cellrowborder" valign="top" headers="mcps1.2.4.1.1 "><p id="p116111718218"><a name="p116111718218"></a><a name="p116111718218"></a>LOS_MemFree</p>
77</td>
78<td class="cellrowborder" valign="top" headers="mcps1.2.4.1.2 "><p id="p1569175218"><a name="p1569175218"></a><a name="p1569175218"></a>Releases the memory allocated from the specified dynamic memory.</p>
79</td>
80</tr>
81<tr id="row19101718144518"><td class="cellrowborder" valign="top" headers="mcps1.2.4.1.1 "><p id="p161417225"><a name="p161417225"></a><a name="p161417225"></a>LOS_MemRealloc</p>
82</td>
83<td class="cellrowborder" valign="top" headers="mcps1.2.4.1.2 "><p id="p56181718219"><a name="p56181718219"></a><a name="p56181718219"></a>Re-allocates a memory block of the required size and copies data from the original block to the newly allocated bock. If the new memory block is successfully allocated, the original memory block will be released.</p>
84</td>
85</tr>
86<tr id="row1346314166464"><td class="cellrowborder" valign="top" headers="mcps1.2.4.1.1 "><p id="p10610171528"><a name="p10610171528"></a><a name="p10610171528"></a>LOS_MemAllocAlign</p>
87</td>
88<td class="cellrowborder" valign="top" headers="mcps1.2.4.1.2 "><p id="p26171714214"><a name="p26171714214"></a><a name="p26171714214"></a>Allocates the memory of the specified size and aligned based on the specified bytes from a dynamic memory pool.</p>
89</td>
90</tr>
91<tr id="row28531740101112"><td class="cellrowborder" rowspan="4" valign="top" width="12.85128512851285%" headers="mcps1.2.4.1.1 "><p id="p39818810129"><a name="p39818810129"></a><a name="p39818810129"></a>Obtaining memory pool information</p>
92</td>
93<td class="cellrowborder" valign="top" width="29.8029802980298%" headers="mcps1.2.4.1.2 "><p id="p16981986123"><a name="p16981986123"></a><a name="p16981986123"></a>LOS_MemPoolSizeGet</p>
94</td>
95<td class="cellrowborder" valign="top" width="57.34573457345735%" headers="mcps1.2.4.1.3 "><p id="p129820881212"><a name="p129820881212"></a><a name="p129820881212"></a>Obtains the total size of the specified dynamic memory pool.</p>
96</td>
97</tr>
98<tr id="row34281341171114"><td class="cellrowborder" valign="top" headers="mcps1.2.4.1.1 "><p id="p0987831214"><a name="p0987831214"></a><a name="p0987831214"></a>LOS_MemTotalUsedGet</p>
99</td>
100<td class="cellrowborder" valign="top" headers="mcps1.2.4.1.2 "><p id="p1598889124"><a name="p1598889124"></a><a name="p1598889124"></a>Obtains the total memory usage of the specified dynamic memory pool.</p>
101</td>
102</tr>
103<tr id="row112644551119"><td class="cellrowborder" valign="top" headers="mcps1.2.4.1.1 "><p id="p398208201215"><a name="p398208201215"></a><a name="p398208201215"></a>LOS_MemInfoGet</p>
104</td>
105<td class="cellrowborder" valign="top" headers="mcps1.2.4.1.2 "><p id="p139815820126"><a name="p139815820126"></a><a name="p139815820126"></a>Obtains the memory structure information of the specified memory pool, including the free memory, used memory, number of free memory blocks, number of used memory blocks, and maximum size of the free memory block.</p>
106</td>
107</tr>
108<tr id="row1357684518110"><td class="cellrowborder" valign="top" headers="mcps1.2.4.1.1 "><p id="p3981383125"><a name="p3981383125"></a><a name="p3981383125"></a>LOS_MemPoolList</p>
109</td>
110<td class="cellrowborder" valign="top" headers="mcps1.2.4.1.2 "><p id="p998148101218"><a name="p998148101218"></a><a name="p998148101218"></a>Prints information about all initialized memory pools in the system, including the start address, size, total free memory, used memory, maximum size of the free memory block, number of free memory blocks, and number of used memory blocks of each memory pool. It is valid only when <strong id="b18583195311398"><a name="b18583195311398"></a><a name="b18583195311398"></a>LOSCFG_MEM_MUL_POOL</strong> is enabled.</p>
111</td>
112</tr>
113<tr id="row14824879135"><td class="cellrowborder" valign="top" width="12.85128512851285%" headers="mcps1.2.4.1.1 "><p id="p1058973361319"><a name="p1058973361319"></a><a name="p1058973361319"></a>Obtaining memory block information</p>
114</td>
115<td class="cellrowborder" valign="top" width="29.8029802980298%" headers="mcps1.2.4.1.2 "><p id="p989115206287"><a name="p989115206287"></a><a name="p989115206287"></a>LOS_MemFreeNodeShow</p>
116</td>
117<td class="cellrowborder" valign="top" width="57.34573457345735%" headers="mcps1.2.4.1.3 "><p id="p437618158141"><a name="p437618158141"></a><a name="p437618158141"></a>Prints the size and number of free memory blocks in the specified memory pool.</p>
118</td>
119</tr>
120<tr id="row0715201211155"><td class="cellrowborder" valign="top" width="12.85128512851285%" headers="mcps1.2.4.1.1 "><p id="p13599202711513"><a name="p13599202711513"></a><a name="p13599202711513"></a>Checking memory pool integrity</p>
121</td>
122<td class="cellrowborder" valign="top" width="29.8029802980298%" headers="mcps1.2.4.1.2 "><p id="p5784183891513"><a name="p5784183891513"></a><a name="p5784183891513"></a>LOS_MemIntegrityCheck</p>
123</td>
124<td class="cellrowborder" valign="top" width="57.34573457345735%" headers="mcps1.2.4.1.3 "><p id="p15644611153"><a name="p15644611153"></a><a name="p15644611153"></a>Checks the integrity of the specified memory pool. It is valid only when <strong id="b1827512584018"><a name="b1827512584018"></a><a name="b1827512584018"></a>LOSCFG_BASE_MEM_NODE_INTEGRITY_CHECK</strong> is enabled.</p>
125</td>
126</tr>
127</tbody>
128</table>
129
130>![](../public_sys-resources/icon-note.gif) **NOTE:**
131>-   The dynamic memory module manages memory through control block structures, which consume extra memory. Therefore, the actual memory space available to users is less than the value of  **OS\_SYS\_MEM\_SIZE**.
132>-   The  **LOS\_MemAllocAlign**  and  **LOS\_MemMallocAlign**  APIs consume extra memory for memory alignment, which may cause memory loss. When the memory used for alignment is freed up, the lost memory will be reclaimed.
133
134### How to Develop<a name="section07271773592"></a>
135
136The typical development process of dynamic memory is as follows:
137
1381.  Call the  **LOS\_MemInit**  API to initialize a memory pool.
139
140    After a memory pool is initialized, a memory pool control header and end node will be generated, and the remaining memory is marked as free nodes. The end node is the last node in the memory pool, and its size is  **0**.
141
142
1431.  Call the  **LOS\_MemAlloc**  API to allocate dynamic memory of any size.
144
145    The system checks whether the dynamic memory pool has free memory blocks greater than the requested size. If yes, the system allocates a memory block and returns the pointer to the memory block. If no, the system returns NULL. If the memory block allocated is greater than the requested size, the system splits the memory block and inserts the remaining memory block to the free list.
146
147
1481.  Call the  **LOS\_MemFree**  API to release dynamic memory.
149
150    The released memory block can be reused. When  **LOS\_MemFree**  is called, the memory block will be reclaimed and marked as free nodes. When memory blocks are reclaimed, adjacent free nodes are automatically merged.
151
152
153### Development Example<a name="section84931234145913"></a>
154
155This example implements the following:
156
1571.  Initialize a dynamic memory pool.
1582.  Allocate a memory block from the dynamic memory pool.
1593.  Store a piece of data in the memory block.
1604.  Print the data in the memory block.
1615.  Release the memory block.
162
163The sample code is as follows:
164
165```
166#include "los_memory.h"
167
168#define TEST_POOL_SIZE (2*1024*1024)
169__attribute__((aligned(4))) UINT8 g_testPool[TEST_POOL_SIZE];
170
171VOID Example_DynMem(VOID)
172{
173    UINT32 *mem = NULL;
174    UINT32 ret;
175
176 /* Initialize the memory pool. */
177    ret = LOS_MemInit(g_testPool, TEST_POOL_SIZE);
178    if (LOS_OK  == ret) {
179        printf("Mem init success!\n");
180    } else {
181        printf("Mem init failed!\n");
182        return;
183    }
184
185    /* Allocate memory.*/
186    mem = (UINT32 *)LOS_MemAlloc(g_testPool, 4);
187    if (NULL == mem) {
188        printf("Mem alloc failed!\n");
189        return;
190    }
191    printf("Mem alloc success!\n");
192
193    /* Assign a value.*/
194    *mem = 828;
195    printf("*mem = %d\n", *mem);
196
197    /* Release memory.*/
198    ret = LOS_MemFree(g_testPool, mem);
199    if (LOS_OK == ret) {
200        printf("Mem free success!\n");
201    } else {
202        printf("Mem free failed!\n");
203    }
204
205    return;
206}
207UINT32 ExampleDynMemEntry(VOID)
208{
209    UINT32 ret;
210    TSK_INIT_PARAM_S initParam = {0};
211    initParam.pfnTaskEntry = (TSK_ENTRY_FUNC)Example_DynMem;
212    initParam.usTaskPrio = 10;
213    initParam.pcName = "Example_DynMem";
214    initParam.uwStackSize = LOSCFG_BASE_CORE_TSK_DEFAULT_STACK_SIZE;
215    initParam.uwResved   = LOS_TASK_STATUS_DETACHED;
216
217    /* Create a task with a higher priority. The task will not be executed immediately after being created, because task scheduling is locked.*/
218    ret = LOS_TaskCreate(&g_taskHiID, &initParam);
219    if (ret != LOS_OK) {
220        LOS_TaskUnlock();
221        PRINTK("Example_DynMem create Failed! ret=%d\n", ret);
222        return LOS_NOK;
223    }
224    PRINTK("Example_DynMem create Success!\n");
225    while(1){};
226    return LOS_OK;
227}
228```
229
230### Verification<a name="section165233233917"></a>
231
232The output is as follows:
233
234```
235Mem init success!
236Mem alloc success!
237*mem = 828
238Mem free success!
239```
240
241