1. 静态内存管理
-
结构体
struct rt_mempool { struct rt_object parent; /**< 继承自 ipc_object 类 */ void *start_address; /**< 内存池起始地址 */ rt_size_t size; /**< 内存池的大小 */ rt_size_t block_size; /**< 内存块的大小 */ rt_uint8_t *block_list; /**< 内存块链表头 */ rt_size_t block_total_count; /**< 内存池中内存块的总数量 */ rt_size_t block_free_count; /**< 内存池中空闲内存块的数量 */ rt_list_t suspend_thread; /**< 被挂起的线程列表 */ }; typedef struct rt_mempool *rt_mp_t;
-
常用函数
/** * This function will create a mempool object and allocate the memory pool from * heap. * * @param name the name of memory pool * @param block_count the count of blocks in memory pool * @param block_size the size for each block * * @return the created mempool object */ rt_mp_t rt_mp_create(const char *name, rt_size_t block_count, rt_size_t block_size); /** * This function will allocate a block from memory pool * * @param mp the memory pool object * @param time the waiting time * * @return the allocated memory block or RT_NULL on allocated failed */ void *rt_mp_alloc(rt_mp_t mp, rt_int32_t time); /** * This function will release a memory block * * @param block the address of memory block to be released */ void rt_mp_free(void *block); /** * This function will delete a memory pool and release the object memory. * * @param mp the memory pool object * * @return RT_EOK */ rt_err_t rt_mp_delete(rt_mp_t mp)
-
静态内存池从被初始化到被分配一个内存块,再被分配一个内存块,然后被释放一个内存块,再被释放一个内存块,这一过程内存池结构体的成员是如何变化的呢?内存池池是如何被使用的呢?下图展示了这一过程各变量的变化情况:
2. 动态内存管理
-
结构体、全局常用宏以及相关局部变量定义
#define HEAP_MAGIC 0x1ea0 struct heap_mem { rt_uint16_t magic; rt_uint16_t used; rt_size_t next, prev; }; static rt_uint8_t *heap_ptr; static struct heap_mem *heap_end; /* 指向堆末端数据头 */ static struct heap_mem *lfree; /* 指向最低空闲数据块的指针 */
-
常用函数
/** * @ingroup SystemInit * * This function will initialize system heap memory. * * @param begin_addr the beginning address of system heap memory. * @param end_addr the end address of system heap memory. */ void rt_system_heap_init(void *begin_addr, void *end_addr); /** * Allocate a block of memory with a minimum of 'size' bytes. * * @param size is the minimum size of the requested block in bytes. * * @return pointer to allocated memory or NULL if no free memory was found. */ void *rt_malloc(rt_size_t size); /** * This function will release the previously allocated memory block by * rt_malloc. The released memory block is taken back to system heap. * * @param rmem the address of memory which will be released */ void rt_free(void *rmem);
-
从堆(HEAP)被初始化到被分配内存,再被释放内存,各相关变量以及堆空间的变化情况如下图所示: