Search code examples
microcontrollermicroprocessors

Stack memory allocation in a microcontroller


How to determine stack memory needed for a particular programm in a microcontroller? For example lets say i have a programm which internally may have many subroutines or threads.Before i start executing program I want to fix the stack size for this program.How do i mark end point for stack.


Solution

  • I assume you are talking about a C language project, with no dynamic allocation of memory. An exact calculation of the stack usage is very long and complicated. You need to know at least the stack usage for each function and the call-graph (the compiler can provide this information). Furthermore: is there an operating system? Each thread needs its own stack. Are there interrupt routines? The total stack usage is the sum of the contribution of each cuncurrent execution flow.

    In many cases an empirical method is more effective, i.e. a run time measure of the usage of the stack. For example, you can fill the whole stack area with fixed pattern, then run a significative test, and then check the size of the "dirty" area. The actual size can be calculated by applying a safety margin, for example +50%.