/*
* 第三版,优化free,只需要判断前驱和后继就行,不需要再遍历整个链表
*/
#include <stdint.h>
#define MEM_USED 1
#define MEM_UNUSED 0
#define MEM_SIZE 1024 * 10
#define HEAD_NODE &memeryPool[0]
#define BLOCK_SIZE sizeof(struct MemBlock)
#define MEM_SIZE_MAX (0x7FFF - BLOCK_SIZE)
char memeryPool[MEM_SIZE] = {
0};
/* 每个字节都是宝,对单片机来说,内存池应该不大于65k,所以size 取 unsigned short可行 */
#pragma pack(1)
struct MemBlock {
struct MemBlock *next;
uint16_t size : 15;
uint8_t state : 1;
};
#pragma pack()
void LaMemInit(void)
{
for (int i = 0; i < sizeof(memeryPool); i++) {
memeryPool[i] = 0;
}
struct MemBlock *head = (struct MemBlock *)HEAD_NODE;
head->next = head;
head->state = MEM_UNUSED;
head->size = MEM_SIZE - BLOCK_SIZE;
}
/* 优先使用链表前面节点的地址 */
void *LaMalloc(uint16_t len)
{
if ((len == 0) || (len > MEM_SIZE_MAX)) {
return NULL;
单片机实现内存管理
最新推荐文章于 2024-05-18 00:39:06 发布