static void prvHeapInit( void ) /* PRIVILEGED_FUNCTION */
{
BlockLink_t * pxFirstFreeBlock;
uint8_t * pucAlignedHeap;
portPOINTER_SIZE_TYPE uxAddress;
/* 获取内存堆的大小, 即配置项 configTOTAL_HEAP_SIZE 的值 */
size_t xTotalHeapSize = configTOTAL_HEAP_SIZE;
/* Ensure the heap starts on a correctly aligned boundary. */
/* 获取内存堆的起始地址 */
uxAddress = ( portPOINTER_SIZE_TYPE ) ucHeap;
/* 将内存堆的起始地址按 portBYTE_ALIGNMENT 字节向上对齐
* 并且重新计算地址对齐后内存堆的大小
* uxAddress & 0x0111 ,8 字节对齐
* 例如 0x0100,与运算不为0,所以没有对齐
*/
if( ( uxAddress & portBYTE_ALIGNMENT_MASK ) != 0 )
{
uxAddress += ( portBYTE_ALIGNMENT - 1 );
uxAddress &= ~( ( portPOINTER_SIZE_TYPE ) portBYTE_ALIGNMENT_MASK );
/* 得到字节对齐后的地址 */
/* 字节对齐后剩余总大小,舍弃一部分内存 */
xTotalHeapSize -= uxAddress - ( portPOINTER_SIZE_TYPE ) ucHeap;
}
/* 获取对齐后的地址 */
pucAlignedHeap = ( uint8_t * ) uxAddress;
/* xStart is used to hold a pointer to the first item in the list of free
* blocks. The void cast is used to prevent compiler warnings. */
/* xStart 内存块的下一个内存块指向内存堆 */
xStart.pxNextFreeBlock = ( void * ) pucAlignedHeap;
/* xStart 内存块的大小固定为 0 */
xStart.xBlockSize = ( size_t ) 0;
/* pxEnd is used to mark the end of the list of free blocks and is inserted
* at the end of the heap space. */
/* 从内存堆的末尾与空出一个内存块结构体的内存
* 并让 pxEnd 指向这个内存块
*/
/* 获取内存堆的结束地址 */
uxAddress = ( ( portPOINTER_SIZE_TYPE ) pucAlignedHeap ) + xTotalHeapSize;
/* 为 pxEnd 内存块预留内存空间 */
uxAddress -= xHeapStructSize;
/* 地址按 portBYTE_ALIGNMENT 字节向下对齐 */
uxAddress &= ~( ( portPOINTER_SIZE_TYPE ) portBYTE_ALIGNMENT_MASK );
/* 设置 pxEnd */
pxEnd = ( BlockLink_t * ) uxAddress;
/* pxEnd 内存块的大小固定为 0 */
pxEnd->xBlockSize = 0;
/* pxEnd 指向的内存块没有下一个内存块 */
pxEnd->pxNextFreeBlock = NULL;
/* To start with there is a single free block that is sized to take up the
* entire heap space, minus the space taken by pxEnd. */
/* 将内存堆作为一个空闲内存块 */
pxFirstFreeBlock = ( BlockLink_t * ) pucAlignedHeap;
/* 设置空闲内存块的大小
* 空闲内存块的大小为 pxEnd 指向的地址减内存块结构体的大小
*/
pxFirstFreeBlock->xBlockSize = ( size_t ) ( uxAddress - ( portPOINTER_SIZE_TYPE ) pxFirstFreeBlock );
/* 空闲内存块的下一个内存块指向 pxEnd */
pxFirstFreeBlock->pxNextFreeBlock = pxEnd;
/* Only one block exists - and it covers the entire usable heap space. */
/* 此时内存堆中只有一个空闲内存块,
* 并且这个内存块覆盖了整个内存堆空间
*/
/* 历史剩余堆栈最小 */
xMinimumEverFreeBytesRemaining = pxFirstFreeBlock->xBlockSize;
/* 当前空闲堆栈大小 */
xFreeBytesRemaining = pxFirstFreeBlock->xBlockSize;
}
FreeRTOS内存堆初始化函数prvHeapInit源码分析(10.5.1版本)
于 2024-01-08 23:17:14 首次发布
![](https://img-home.csdnimg.cn/images/20240709112858.png)