Rtthread 内存管理

article/2025/8/25 22:03:25

Rtthread 堆内存管理

#define HEAP_MAGIC 0x1ea0
struct heap_mem
{/* magic and used flag */rt_uint16_t magic; //魔数,固定值rt_uint16_t used;  //使用标记,1为该内存已经被使用rt_size_t next, prev; //双向链表偏移
};
#define MIN_SIZE 12 //一次申请的存size不能低于MIN_SIZE
#define MIN_SIZE_ALIGNED     RT_ALIGN(MIN_SIZE, RT_ALIGN_SIZE) //最小值4对齐,依然为12
#define SIZEOF_STRUCT_MEM    RT_ALIGN(sizeof(struct heap_mem), RT_ALIGN_SIZE)//mem数据结构对齐后的大小(12)/** pointer to the heap: for alignment, heap_ptr is now a pointer instead of an array */
static rt_uint8_t *heap_ptr; //4对齐的堆的首地址
/** the last entry, always unused! */
static struct heap_mem *heap_end; //堆的结尾
static struct heap_mem *lfree;   /* pointer to the lowest free block 当前堆空闲内存块指针*/static struct rt_semaphore heap_sem; //条件变量
static rt_size_t mem_size_aligned; //堆总内存大小(对齐后)#ifdef RT_MEM_STATS
static rt_size_t used_mem, max_mem; //debug信息
#endif

在这里插入图片描述

堆内存初始化

/*** @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)
{struct heap_mem *mem;rt_ubase_t begin_align = RT_ALIGN((rt_ubase_t)begin_addr, RT_ALIGN_SIZE);//向上4字节对齐rt_ubase_t end_align   = RT_ALIGN_DOWN((rt_ubase_t)end_addr, RT_ALIGN_SIZE);//向下4字节对齐RT_DEBUG_NOT_IN_INTERRUPT;//不允许在中断处理函数中调用/* alignment addr 内存总量至少为2个SIZEOF_STRUCT_MEM大小(12*2=24 byte)*/if ((end_align > (2 * SIZEOF_STRUCT_MEM)) &&((end_align - 2 * SIZEOF_STRUCT_MEM) >= begin_align)){/* calculate the aligned memory size 计算对齐后总的mem_size*/mem_size_aligned = end_align - begin_align - 2 * SIZEOF_STRUCT_MEM;}else{rt_kprintf("mem init, error begin address 0x%x, and end address 0x%x\n",(rt_ubase_t)begin_addr, (rt_ubase_t)end_addr);return;}/* point to begin address of heap */heap_ptr = (rt_uint8_t *)begin_align;//保存堆内存首地址RT_DEBUG_LOG(RT_DEBUG_MEM, ("mem init, heap begin address 0x%x, size %d\n",(rt_ubase_t)heap_ptr, mem_size_aligned));/* initialize the start of the heap */mem        = (struct heap_mem *)heap_ptr;mem->magic = HEAP_MAGIC;mem->next  = mem_size_aligned + SIZEOF_STRUCT_MEM;mem->prev  = 0;mem->used  = 0;/* initialize the end of the heap */heap_end        = (struct heap_mem *)&heap_ptr[mem->next];heap_end->magic = HEAP_MAGIC;heap_end->used  = 1;heap_end->next  = mem_size_aligned + SIZEOF_STRUCT_MEM;heap_end->prev  = mem_size_aligned + SIZEOF_STRUCT_MEM;//互斥信号量初始化rt_sem_init(&heap_sem, "heap", 1, RT_IPC_FLAG_FIFO);/* initialize the lowest-free pointer to the start of the heap */lfree = (struct heap_mem *)heap_ptr;
}

在这里插入图片描述

rt_malloc实现

/*** @addtogroup MM*//**@{*//*** 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)
{rt_size_t ptr, ptr2;struct heap_mem *mem, *mem2;if (size == 0)return RT_NULL;//禁止中断处理函数调用rt_mallocRT_DEBUG_NOT_IN_INTERRUPT;if (size != RT_ALIGN(size, RT_ALIGN_SIZE))RT_DEBUG_LOG(RT_DEBUG_MEM, ("malloc size %d, but align to %d\n",size, RT_ALIGN(size, RT_ALIGN_SIZE)));elseRT_DEBUG_LOG(RT_DEBUG_MEM, ("malloc size %d\n", size));/* alignment size */size = RT_ALIGN(size, RT_ALIGN_SIZE);if (size > mem_size_aligned){RT_DEBUG_LOG(RT_DEBUG_MEM, ("no memory\n"));return RT_NULL;}/* every data block must be at least MIN_SIZE_ALIGNED long */if (size < MIN_SIZE_ALIGNED)size = MIN_SIZE_ALIGNED;/* take memory semaphore */rt_sem_take(&heap_sem, RT_WAITING_FOREVER);//遍历堆内存,寻找满足size大小要求的//lfree - heap_ptr获取到第一块空闲内存相对于堆首地址的偏移//ptr + size < mem_size_aligned等价于://ptr + (size + SIZEOF_STRUCT_MEM) < mem_size_aligned + SIZEOF_STRUCT_MEMfor (ptr = (rt_uint8_t *)lfree - heap_ptr;ptr < mem_size_aligned - size; ptr = ((struct heap_mem *)&heap_ptr[ptr])->next){//取出空闲内存的信息块mem = (struct heap_mem *)&heap_ptr[ptr];//内存未被使用,并且该内存块的大小完全满足size的需求if ((!mem->used) && (mem->next - (ptr + SIZEOF_STRUCT_MEM)) >= size){/* mem is not used and at least perfect fit is possible:* mem->next - (ptr + SIZEOF_STRUCT_MEM) gives us the 'user data size' of mem *///该内存块空间大于size + (SIZEOF_STRUCT_MEM + MIN_SIZE_ALIGNED),那么需要对该内存块分割//也就是说,该内存块在分出size大小的空间后,至少还有SIZEOF_STRUCT_MEM + MIN_SIZE_ALIGNED//大小的内存空间,就需要对该内存块进行分割。if (mem->next - (ptr + SIZEOF_STRUCT_MEM) >=(size + SIZEOF_STRUCT_MEM + MIN_SIZE_ALIGNED)){/* (in addition to the above, we test if another struct heap_mem (SIZEOF_STRUCT_MEM) containing* at least MIN_SIZE_ALIGNED of data also fits in the 'user data space' of 'mem')* -> split large block, create empty remainder,* remainder must be large enough to contain MIN_SIZE_ALIGNED data: if* mem->next - (ptr + (2*SIZEOF_STRUCT_MEM)) == size,* struct heap_mem would fit in but no data between mem2 and mem2->next* @todo we could leave out MIN_SIZE_ALIGNED. We would create an empty*       region that couldn't hold data, but when mem->next gets freed,*       the 2 regions would be combined, resulting in more free memory*///分割准备,计算要分割的地址ptr2 = ptr + SIZEOF_STRUCT_MEM + size;/* create mem2 struct */mem2       = (struct heap_mem *)&heap_ptr[ptr2];mem2->magic = HEAP_MAGIC;mem2->used = 0;mem2->next = mem->next;//插入链表mem2->prev = ptr;/* and insert it between mem and mem->next */mem->next = ptr2;mem->used = 1;//标记mem内存已经使用//切割的内存的下一个内存块不是最后一个内存块,就将下一个内存块的prev指向//当前切割出来的内存块if (mem2->next != mem_size_aligned + SIZEOF_STRUCT_MEM){((struct heap_mem *)&heap_ptr[mem2->next])->prev = ptr2;}
#ifdef RT_MEM_STATSused_mem += (size + SIZEOF_STRUCT_MEM);if (max_mem < used_mem)max_mem = used_mem;
#endif}else{/* (a mem2 struct does no fit into the user data space of mem and mem->next will always* be used at this point: if not we have 2 unused structs in a row, plug_holes should have* take care of this).* -> near fit or excact fit: do not split, no mem2 creation* also can't move mem->next directly behind mem, since mem->next* will always be used at this point!*///如果该内存块不满足分割条件,则直接返回该内存mem->used = 1;
#ifdef RT_MEM_STATSused_mem += mem->next - ((rt_uint8_t *)mem - heap_ptr);if (max_mem < used_mem)max_mem = used_mem;
#endif}/* set memory block magic */mem->magic = HEAP_MAGIC;if (mem == lfree)//只有在使用lfree指向的内存块后才更新lfree{/* Find next free block after mem and update lowest free pointer */while (lfree->used && lfree != heap_end)lfree = (struct heap_mem *)&heap_ptr[lfree->next];RT_ASSERT(((lfree == heap_end) || (!lfree->used)));}rt_sem_release(&heap_sem);//释放互斥信号量RT_ASSERT((rt_ubase_t)mem + SIZEOF_STRUCT_MEM + size <= (rt_ubase_t)heap_end);RT_ASSERT((rt_ubase_t)((rt_uint8_t *)mem + SIZEOF_STRUCT_MEM) % RT_ALIGN_SIZE == 0);RT_ASSERT((((rt_ubase_t)mem) & (RT_ALIGN_SIZE - 1)) == 0);RT_DEBUG_LOG(RT_DEBUG_MEM,("allocate memory at 0x%x, size: %d\n",(rt_ubase_t)((rt_uint8_t *)mem + SIZEOF_STRUCT_MEM),(rt_ubase_t)(mem->next - ((rt_uint8_t *)mem - heap_ptr))));RT_OBJECT_HOOK_CALL(rt_malloc_hook,(((void *)((rt_uint8_t *)mem + SIZEOF_STRUCT_MEM)), size));/* return the memory data except mem struct */return (rt_uint8_t *)mem + SIZEOF_STRUCT_MEM;}}rt_sem_release(&heap_sem);return RT_NULL;
}

总结一下rt_malloc的流程:
1.检查申请内存size大小是否向上4对齐,没有的话先做对齐。
2.检查对齐后的申请的内存大小是否超过堆总内存大小。
3.检查对齐后申请的内存是否小于最小size。
4.计算出空闲地址相对于首地址的偏移量,并开始循环查找满足size内存申请的内存块。
5.找到尚未使用,并且满足size大小条件的内存块。
6.判断该内存块是否大于size + SIZEOF_STRUCT_MEM + MIN_SIZE_ALIGNED,大于则对其进行分割
否则直接将整块内存分给申请者。

rt_realloc

/*** This function will change the previously allocated memory block.** @param rmem pointer to memory allocated by rt_malloc* @param newsize the required new size** @return the changed memory block address*/
void *rt_realloc(void *rmem, rt_size_t newsize)
{rt_size_t size;rt_size_t ptr, ptr2;struct heap_mem *mem, *mem2;void *nmem;RT_DEBUG_NOT_IN_INTERRUPT;/* alignment size */newsize = RT_ALIGN(newsize, RT_ALIGN_SIZE);if (newsize > mem_size_aligned){RT_DEBUG_LOG(RT_DEBUG_MEM, ("realloc: out of memory\n"));return RT_NULL;}else if (newsize == 0){rt_free(rmem);return RT_NULL;}/* allocate a new memory block */if (rmem == RT_NULL)return rt_malloc(newsize);rt_sem_take(&heap_sem, RT_WAITING_FOREVER);if ((rt_uint8_t *)rmem < (rt_uint8_t *)heap_ptr ||(rt_uint8_t *)rmem >= (rt_uint8_t *)heap_end){/* illegal memory */rt_sem_release(&heap_sem);return rmem;}//获取内存的头信息mem = (struct heap_mem *)((rt_uint8_t *)rmem - SIZEOF_STRUCT_MEM);//获取当前内存块相对于堆首地址的偏移ptr = (rt_uint8_t *)mem - heap_ptr;size = mem->next - ptr - SIZEOF_STRUCT_MEM;//计算当前内存块拥有的内存sizeif (size == newsize){/* the size is the same as */rt_sem_release(&heap_sem);return rmem;}//如果size满足newsize的大小需求,则进行分割if (newsize + SIZEOF_STRUCT_MEM + MIN_SIZE < size){/* split memory block */
#ifdef RT_MEM_STATSused_mem -= (size - newsize);
#endifptr2 = ptr + SIZEOF_STRUCT_MEM + newsize;mem2 = (struct heap_mem *)&heap_ptr[ptr2];mem2->magic = HEAP_MAGIC;mem2->used = 0;mem2->next = mem->next;mem2->prev = ptr;
#ifdef RT_USING_MEMTRACErt_mem_setname(mem2, "    ");
#endifmem->next = ptr2;if (mem2->next != mem_size_aligned + SIZEOF_STRUCT_MEM){((struct heap_mem *)&heap_ptr[mem2->next])->prev = ptr2;}if (mem2 < lfree){/* the splited struct is now the lowest */lfree = mem2;}plug_holes(mem2);rt_sem_release(&heap_sem);return rmem;}rt_sem_release(&heap_sem);/* expand memory *///当前内存块不满足new size,将重新申请内存nmem = rt_malloc(newsize);if (nmem != RT_NULL) /* check memory */{rt_memcpy(nmem, rmem, size < newsize ? size : newsize);rt_free(rmem);}return nmem;
}

rt_free

/*** 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)
{struct heap_mem *mem;if (rmem == RT_NULL)return;//禁止在中断处理函数中调用该函数RT_DEBUG_NOT_IN_INTERRUPT;RT_ASSERT((((rt_ubase_t)rmem) & (RT_ALIGN_SIZE - 1)) == 0);RT_ASSERT((rt_uint8_t *)rmem >= (rt_uint8_t *)heap_ptr &&(rt_uint8_t *)rmem < (rt_uint8_t *)heap_end);RT_OBJECT_HOOK_CALL(rt_free_hook, (rmem));if ((rt_uint8_t *)rmem < (rt_uint8_t *)heap_ptr ||(rt_uint8_t *)rmem >= (rt_uint8_t *)heap_end){RT_DEBUG_LOG(RT_DEBUG_MEM, ("illegal memory\n"));return;}/* Get the corresponding struct heap_mem ... *///获取要free的内存的头信息mem = (struct heap_mem *)((rt_uint8_t *)rmem - SIZEOF_STRUCT_MEM);RT_DEBUG_LOG(RT_DEBUG_MEM,("release memory 0x%x, size: %d\n",(rt_ubase_t)rmem,(rt_ubase_t)(mem->next - ((rt_uint8_t *)mem - heap_ptr))));/* protect the heap from concurrent access */rt_sem_take(&heap_sem, RT_WAITING_FOREVER);//check 状态/* ... which has to be in a used state ... */if (!mem->used || mem->magic != HEAP_MAGIC){rt_kprintf("to free a bad data block:\n");rt_kprintf("mem: 0x%08x, used flag: %d, magic code: 0x%04x\n", mem, mem->used, mem->magic);}RT_ASSERT(mem->used);RT_ASSERT(mem->magic == HEAP_MAGIC);/* ... and is now unused. */mem->used  = 0;mem->magic = HEAP_MAGIC;//当前释放的内存小于空闲内存的地址,就更新空闲内存的地址if (mem < lfree){/* the newly freed struct is now the lowest */lfree = mem;}#ifdef RT_MEM_STATSused_mem -= (mem->next - ((rt_uint8_t *)mem - heap_ptr));
#endif/* finally, see if prev or next are free also *///合并空闲内存plug_holes(mem);rt_sem_release(&heap_sem);
}static void plug_holes(struct heap_mem *mem)
{struct heap_mem *nmem;struct heap_mem *pmem;RT_ASSERT((rt_uint8_t *)mem >= heap_ptr);RT_ASSERT((rt_uint8_t *)mem < (rt_uint8_t *)heap_end);RT_ASSERT(mem->used == 0);/* plug hole forward *///获取Next内存块nmem = (struct heap_mem *)&heap_ptr[mem->next];if (mem != nmem &&nmem->used == 0 &&(rt_uint8_t *)nmem != (rt_uint8_t *)heap_end){/* if mem->next is unused and not end of heap_ptr,* combine mem and mem->next*/if (lfree == nmem){lfree = mem;}//删除NEXT链表节点mem->next = nmem->next;((struct heap_mem *)&heap_ptr[nmem->next])->prev = (rt_uint8_t *)mem - heap_ptr;}/* plug hole backward */pmem = (struct heap_mem *)&heap_ptr[mem->prev];if (pmem != mem && pmem->used == 0){/* if mem->prev is unused, combine mem and mem->prev */if (lfree == mem){lfree = pmem;}pmem->next = mem->next;((struct heap_mem *)&heap_ptr[mem->next])->prev = (rt_uint8_t *)pmem - heap_ptr;}
}

http://chatgpt.dhexx.cn/article/DJxabSAW.shtml

相关文章

RT-Thread学习

一、入门 RT-Thread官网  官网文档   Rt-thread学习文档  RT-Thread官方bilibili视频号   GD32官网 教你动手移植RT-Thread到国产MCU    如何移植RT-Thread到GD32单片机上&#xff08;非studio版&#xff09; 东方青讲RT-Thread  RT-Thread内核入门指南 RT-Thread…

RT Thread之ADC电压读取

官网连接&#xff1a;https://docs.rt-thread.org/#/rt-thread-version/rt-thread-standard/programming-manual/device/adc/adc 一、配置步骤&#xff1a; 1、用cubemx配置底层&#xff1b; 2、cubemx配置好的文件替换之前的配置文件&#xff1b; 3、修改Kconfig文件&…

rtthread mqtt

rtthread 以太网 (LAN8720A) 基于以太网的应用mqtt&#xff0c;在**rtthread 以太网 (LAN8720A)**中已经实现了tcp/ip通信正常&#xff0c;接下需要启用mqtt模块&#xff0c; 嵌入式mqtt设备 rtthread 启用mqtt 在rtthread中田间 pahomqtt 软件包&#xff0c;并右键详细配置…

【RTThread】修改Finsh打印串口波特率

这里需要注意得是一定要在hw_board_init初始化完成之后修改串口波特率。 /* 串口设备句柄 */static rt_device_t uart_device RT_NULL;/* 查找系统中的串口设备 */uart_device rt_device_find("uart1"); // 这里/* 串口配置结构体&#xff0c;使用serial.h的宏定义…

RT Thread之 Uart2 操作

官网连接&#xff1a;https://docs.rt-thread.org/#/rt-thread-version/rt-thread-standard/programming-manual/device/uart/uart 通过前面的学习&#xff0c;基本上RT Thread操作步骤都是&#xff0c;先配置单片机底层&#xff0c;然后再通过应用层映射到底层&#xff0c;最…

rtthread

链表 初始化双向链表 rt_inline void rt_list_init(rt_list_t *l) {l->next l->prev l; }插入 rt_inline void rt_list_insert_after(rt_list_t *l, rt_list_t *n) {l->next->prev n;n->next l->next;l->next n;n->prev l; }在NODE1后面插入节…

RT Thread根据开发板制作BSP方法

之前一直不懂怎么使用RT Thread的软件包&#xff0c;感谢网上的大神&#xff0c;看了你们的博客后大概了解一些&#xff0c;在此做下记录。用RT Thread软件包需要RT Thread的系统&#xff0c;但是RT Thread和RT Thread nano不一样&#xff0c;具体区别见 RT Thread官网&#xf…

rtthread开关中断

1 rtthread开关中断函数(cortex-m) /** rt_base_t rt_hw_interrupt_disable();*/ .global rt_hw_interrupt_disable .type rt_hw_interrupt_disable, %function rt_hw_interrupt_disable:MRS r0, PRIMASKCPSID IBX LR/** void rt_hw_interrupt_enable(rt_base_t le…

RTThread入门

RT-Thread入门 1.初识RT-Thread 嵌入式系统是一种完全嵌入在装置或设备内部&#xff0c;为满足特定需求而设计的计算机系统&#xff0c;譬如生活中常见的嵌入式系统就有&#xff1a;电视机顶盒、路由器、电冰箱、微波炉与移动电话等。 嵌入式操作系统是应用于嵌入式系统的软…

什么是RT-Thread?

一、RT-Thread的定义 RT-Thread&#xff0c;全称是 Real Time-Thread&#xff0c; 是一款主要由中国开源社区主导开发的开源实时操作系统&#xff08;许可证GPLv2&#xff09;&#xff0c;包含了实时、嵌入式系统相关的各个组件&#xff1a;TCP/IP协议栈、图形用户界面等。 相…

Redis启动失败的原因及解决方法

跑了近半年的Redis,今天早上来开启电脑运行程序的时候发现提示无法连接redis,暗想自己明明设置了开机自启的阿,以前也一直没问提,今天怎么就连不上了重启了下redis就提示如下错误 网上搜了好久都没找到解决办法,后来想起来去查看了下redis的日志文件 发现提示当前版本的redis无…

redis启动、获取密码及修改密码

一、启动redis服务的两种方式 查看密码是以redis服务已启动的前提下进行的&#xff0c;可直接在服务中右键启动redis或者安装根目录运行cmd输入《redis-server.exe》(不推荐不推荐不推荐&#xff0c;说三遍&#xff0c;命令行启动好像有bug&#xff0c;启动后redis能用&#x…

CentOS安装Redis及redis启动与关闭、配置(详细)

在项目使用redis过程中&#xff0c;在centos7上部署redis&#xff0c;查找相关资料并总结、记录&#xff0c;以备后续查看。 目录 一、Redis介绍 二、在CentOS上部署Redis 1、Redis安装包可以从官网上下载或者直接命令下载 升级到gcc 9.3&#xff1a; 3、Redis配置文件…

Redis启动和连接

一&#xff09;Redis简介 Redis不是简单的键值存储&#xff0c;它实际上是一个数据结构服务器&#xff0c;支持不同类型的值。 备注&#xff1a;由于我电脑是32位操作系统&#xff0c;所有就不提供redis软件下载地址了&#xff0c;请到官网下载使用。 软件解压之后&#xff0…

windows下Redis启动闪退问题解决经验汇总

最近使用Redis又遇到启动闪退的问题&#xff0c;之前记录的解决办法也失败了&#xff0c;一番研究后总算得到解决&#xff0c;感觉已经遇到了网上常见的各种问题&#xff0c;下面总结下。 我下载的是免安装版&#xff0c;解压便可使用。 官网下载传送门&#xff1a;Releases …

Windows下redis启动那些事儿

本文章主要描述我遇到的Windows下redis启动成功但Java项目无法连接问题 1.使用redis可视化工具可以连接&#xff0c;但是到Java项目中就报错连接失败 经过我的多方琢磨&#xff0c;还是密码没有配置正确&#xff0c;虽然是在redis.windows.conf配置文件中配置了 requirepass 密…

redis启动失败问题完美解决

1.输入启动命令redis-server.exe redis.windows.conf启动redis&#xff0c;发现启动失败报错&#xff1a;[8072] 07 May 09:28:52.241 # Creating Server TCP listening socket 127.0.0.1:6379: bind: No error D:\a\Main\redis> redis-server.exe redis.windows.conf[8072]…

windows redis启动

下载好redis后&#xff0c;只需解压。 然后打开dos窗口 进入redis解压目录 cd D:softwareRedis-x64-3.2.100运行下面命令启动 redis-server.exe redis.windows.conf成功启动 还可以把redis加入都开机自启动 redis-server --service-install redis.windows-service.conf …

redis启动和简单使用

redis启动和简单使用 1.redis启动 1.1 找到redis解压的位置,在里面输入cmd回车 1.2 输入redis-server redis.conf指令,然后回车,出现如下界面 注意&#xff1a;该界面不能关闭了 1.3 再进入一次redis解压的位置 输入cmd回车 1.4 输入redis-cli指令后的结果 1.5 补充 当出现…

Redis的启动方式三种

Redis的启动方式三种 启动一个 &#xff0c;进入到redis中的src目录下 在控制台输入指令&#xff1a;redis-server &#xff08;注意&#xff1a;这样启动默认端口是 6379 &#xff09; 进入客户端输入&#xff1a;redis-cli 查看进程&#xff0c;杀死进程 指定端口启动redi…