One method to prevent stack overflow is to track the stack pointer with test and measurement methods. Stack overflow errors are difficult to detect. In most instances, these errors are hard to catch, as there you can only find some fragments of what has happened after the stack has grown beyond itself and been corrupted. If the stack grows into the global area, variables get overwritten, pointers get pushed “off” where they are supposed to be and “go wild,” and corrupted return addresses are out of control.
Figure 1: The purple area illustrates how stack overflow overwrites adjacent memory (in yellow.) (Source: IAR Systems.) If there’s a stack overflow, unless there’s a memory protection unit on the core that you are working with, the stack can grow beyond its allocated space. Thus precautions for stack overflow are trickier. Although stack overflow is an equally terrible event for either non-embedded (desktop) or embedded, memory is much more critical for embedded applications.
If you set the stack too large, you waste memory that could be used elsewhere. How do you set a stack up properly? If you set the stack up with too little space, with not enough memory allocated to the stack, then the stack is going to overflow. The stack is a fixed amount of memory that is set statically by the programmer before execution.
As it grows beyond its allocated space, the dynamic stack contents begin to overwrite other things, such as critical application code and data. Stack overflow is when a function or program uses more memory than is in the stack.
The life span of tracking a function on the stack lasts only as long as the duration of the function, so the stack contents are constantly changing. The stack tracks function arguments, stores local variables, compiler temporaries, return addresses, and interrupt contexts. The stack works “last in, first out,” and tracks local variables as they get pushed onto and popped off the stack. The stack is where processes or tasks “keep notes” on what they need to do the next time the processor becomes available. A stack is like a special buffer, or working memory, where processes are tracked.