FreeRTOS新建任务时 xTaskCreate 函数有这样一段注释
// 代码已简化
/* If the stack grows down then allocate the stack then the TCB so the stack
* does not grow into the TCB. Likewise if the stack grows up then allocate
* the TCB then the stack. */
#if ( portSTACK_GROWTH > 0 ) // 栈向上生长
{
pxNewTCB = ( TCB_t * ) pvPortMallocTcbMem( sizeof( TCB_t ) );
pxNewTCB->pxStack = ( StackType_t * ) pvPortMallocStackMem( ( ( ( size_t ) usStackDepth ) * sizeof( StackType_t ) ) );
}
#else /* portSTACK_GROWTH */ // 栈向下生长
{
StackType_t * = pvPortMallocStackMem( ( ( ( size_t ) usStackDepth ) * sizeof( StackType_t ) ) );
pxNewTCB = ( TCB_t * ) pvPortMallocTcbMem( sizeof( TCB_t ) ); .
pxNewTCB->pxStack = pxStack;
}
#endif /* portSTACK_GROWTH */
会有疑问:那么为什么栈的增长方向与tcb和stack空间申请的顺序有关?
此处有个约定俗成的知识点:默认内存高地址在上,低地址在下。
portSTACK_GROWTH > 0 即 栈向上生长
portSTACK_GROWTH < 0 即 栈向下生长
下图以栈向下生长为例:
当栈向下生长时,需在堆上先申请Stack、后申请TCB(谁先申请谁在堆上的地址较小),否则,Stack在生长的过程中可能会覆盖到TCB的区域:
同理当栈向上生长时需要先申请TCB后申请Stack。