The binary tree approach is used to allocate and release memory.

Source: Internet
Author: User
The binary tree approach is used to allocate and release memory.Although most systems provide memory Dynamic Allocation and release functions (namely, the malloc and free functions in the C language), in embedded development, due to system restrictions, you often need to implement memory management by yourself, if the maximum space that can be dynamically applied on some platforms cannot meet the needs of programming, the memory allocation and release functions provided by some systems may cause a large amount of memory fragments, resulting in insufficient memory, in these cases, you often need to apply for a large memory, and then re-allocate it in this large memory, that is, to create an independent memory management program. In fact, designing a memory management program by yourself has the following advantages: 1. It is easy to monitor the memory usage during the program running, such as whether there is memory leakage or the peak memory usage; 2. Prevent system damages caused by improper Program Design (such as pointer out-of-bounds and wild pointer), so as to easily define the scope of the problem; 3. You can reduce memory fragments by optimizing the memory management algorithm. 4. It facilitates program transplantation. When a program is transplanted to different platforms, you do not need to consider the system memory management, you only need to consider whether you can get a large block of memory. There may be many ways to use the memory allocation and release methods. Here we propose the idea of using a binary tree to manage the memory. Binary Tree is a common data structure and is applied to many algorithms. The definition of binary tree is not described here. The main features of binary tree are as follows: each node in a binary tree has a maximum of two subnodes and a maximum of one parent node. Memory Allocation refers to dividing a large memory block into several smaller memory blocks. The general method is to use the power of 2 as the block size (that is, the memory granularity ), when the size of the memory to be allocated is not equal to the configured memory granularity, find a granularity that is closest to the configured memory size and greater than the configured memory size, this allocation method can be expressed in the form of a binary tree. For example, if 64 bytes are allocated from a 1 kb memory space, the leaf node indicates the split memory block, when you want to find an idle memory block, you should find it in these leaf nodes. If you cannot find it, find a larger idle node for redistribution. The main purpose of using a binary tree is to understand how to recycle idle space. The continuous distribution and release of memory will inevitably cause a large amount of memory fragments, if you do not sort out the memory fragments, no memory is available. Therefore, you must combine the continuous memory space when releasing the free memory to avoid Memory fragments, however, not all contiguous spaces are suitable for merging. For example, memory blocks H, I, J, and K are sequential spaces, and H and K are used, I and j are just released free space. Obviously, I and J can form a larger free space, such as B, however, this not only damages the original idea of Binary trees, but also makes it complicated to merge space H and K in the future, which will increase many algorithms, if you want to determine whether the space I and J have been merged, and each time you release a memory space, you must make a similar judgment on the binary trees at each layer. Although this can reduce the memory fragmentation, however, releasing memory functions is a common function. This calculation workload is unacceptable especially in embedded development. In addition, the above situation is usually rare in the program, therefore, we do not merge such continuous spaces, only Only two leaf nodes with the same parent node are merged. The general idea is: When the memory is cut, a large memory space is always cut into two small memory spaces. When the memory is merged, merge the two memory blocks that are originally separated by the same memory block.. The following describes how to apply for and release memory based on the following idea: 1. Data structure definitionUse an array to define the memory granularity (defined in multiples of 2): # define granularity_number 12 const int memgranularity [granularity_number] = {64,128,256,512,102, 16, 32, 2048, 4096, 0 xFFFF }; create a memory block pointer array (memory bucket) classified by granularity: typedef struct mem_block_info_struct {void * memptr; // memory block pointer mem_block_info_struct * nextblock; // pointer to the next memory block} memblockinfo; typedef struct mem_array_head_struct {memblockinfo * freedmemarray; // memblockinfo * usedmem Array; // pointer to the linked list of used memory blocks} memarrayhead; memarrayhead membucket [granularity_number] = {}; for example, membucket [0] points to a memory block linked list with a memory block size of 4 bytes, and membucket [1] points to a memory block linked list with a memory block size of 8 bytes. You can specify a part of memory before a large block of memory to store the information of each block. For example:

It is necessary to estimate in advance the size of memory to store the information of each memory block. It is easier to estimate the size of a small running program, however, if the program is complicated, you need to use experiments to determine the partition size. You can set a macro definition value in advance. You only need to change this macro definition value in the future, for example:

# Define memory_block_max_number 2048 memblockinfo * memblockarray = NULL; the memory block linked list pointed to by the membucket is sorted from low to high based on the memory block pointer (memptr) value, in fact, you only need to insert a new memory block in an orderly manner according to the pointer value, so as to facilitate searching for nodes in the linked list and improve the search efficiency. 2. Algorithm Implementation1 ), Initialization MethodA. initialize global variables; B. A part of memory block information is separated at the front of the memory block to store the memory block information. C. starting from the remaining memory space, the memory is cut according to the set memory granularity. The cutting principle is to make the total number of memory blocks cut out to the minimum value. The method is to cut the memory by granularity from large to small, if the remaining space is 7680b, the following memory blocks can be cut: 4096b, 2048b, 1024b, and 512b (this means that we first create four Binary Trees with only one node ), these memory block pointers are stored in memblockarray, and the corresponding membucket pointers are directed to memblockarray Based on the granularity and memory block size. 2 ), Dynamic memory allocation method (that is Malloc Function implementation)A. the size of the memory to be allocated is determined based on the size specified in the input parameter. When the allocation size is equal to a specific granularity, it is allocated according to the granularity, if the corresponding size granularity is not found, find a minimum granularity that is larger than the size of the space to be allocated as the allocation space, for example, to allocate 20 bytes of space, A 32-byte space is allocated. B. search for the idle space in the idle linked list based on the granularity: If found, return the idle space pointer and move the corresponding node into the used linked list; if not found, find an idle block with a larger granularity, and split the idle block in half until the desired granularity is obtained, finally, the split idle block is removed from the linked list, and the pointer of the node is set to null. The split idle block pointer is saved to the memblockarray, the newly added array unit content in memblockarray is added to the idle linked list of membucket as nodes (Added by pointer size order). One of the smallest idle blocks is used as the memory block to be returned, and move the memory block into the used linked list. 3) release the memory block method (that is, the free function implementation method) to search for all used linked lists and find the nodes of the same size as the passed pointer, this node is moved from the used linked list to the idle linked list. It is also inserted to the idle linked list in order. If adjacent nodes are found to be contiguous spaces, in addition, the adjacent nodes are originally split from the same large idle memory block (that is, the two child nodes of the same parent node), then the two memory blocks are merged, move the merged memory blocks to a larger idle linked list. If a larger idle linked list shows that memory blocks can be merged, merge them. In this way, until it cannot be merged. Merge idle memory blocks: remove these two memory block nodes from the idle linked list, and move the nodes with small address pointers to the idle linked list with larger granularity according to the memory address size, set all pointer values in the nodes with large address pointers to null. Determine whether two memory blocks are separated from the same large idle memory block: if both memory block 1 and memory block 2 are separated from the same large idle memory block, the following conditions are met: (the preceding memory block + memory block 1) /memory block 1 size: the result is an odd number (the first memory block + memory block 1 + memory block 2)/the size of memory block 2: The result is an even number of 3. advantages and disadvantages of this method 1). Advantages: the implementation method is simple, and the memory fragments generated are small. 2) Disadvantages: the memory space utilization is not high. When the memory allocation requires more memory blocks, a large memory space is wasted because the memory block information needs to be stored, in addition, if the length of the array storing memory block information is fixed, you may need to adjust the size in a specific application, which is not flexible.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.