RAM Usage / Management

scottnortman wrote on Thursday, May 17, 2007:


How does one know how much stack space to allocate to each task?  Also, what about the configTOTAL_HEAP_SIZE option?  How is the heap size related to the memory allocation scheme?

Scott Nortman

rtel wrote on Friday, May 18, 2007:

The amount of stack required by a task is completely dependent on the implementation of the task.  The following items will increase the amount of stack the task requires:

1) High function call nesting depth.

Each time a function is called data is saved to the stack.

2) Local, non static variables.  Each of which is allocated stack space.  This is why you should not declare large structures or arrays as local variables (unless you make them static).

When a task is created its stack is set to 0xa5, so you can always check the high water mark by viewing the memory in a debugger.  The location of the currently used stack can be obtained from the stack pointer of the processor you are using.  Alternatively, using the debugger you can inspect the pxCurrentTCB pointer, which is a pointer to the TCB.  The pxCurrentTCB->pxStack member points to the start of the stack used by the task.  The pxCurrentTCB->pxTopOfStack points to the top of the stack as it was the last time the task entered the Running state.

Also take a look at the function usTaskCheckFreeStackSpace() in tasks.c, this can be used to return the task high water mark.  The lower the number returned the closer the task has come to overflowing its stack.

configTOTAL_HEAP_SIZE defines the size of the block of memory available to the memory allocator used by either the heap_1 or heap_2 schemes.  Memory is grabbed from this pool each time a task or queue is created.  Take a look here:  http://www.freertos.org/a00111.html  if you have not already seen it.