For many embedded developers, the stack seems to be a rather mysterious force. When strange things start to happen and engineers are finally stumped, they begin to wonder what might have happened to the stack. The result is blindly adjusting the size and position of the stack, and so on. But this error is often not related to the stack itself, but how can one be so sure? After all, how many engineers have actually performed the worst-case stack size analysis in practice?
The stack size is statically allocated during compilation, but the stack is used dynamically. As the code executes, the variables needed by the application, return addresses, and other information are continuously stored in the stack. This mechanism causes the stack to continuously grow within the allocated memory. However, this growth sometimes exceeds the capacity limit determined at compile time, resulting in the stack damaging the data in adjacent memory areas.
One way to absolutely ensure that the stack is functioning properly is to implement a stack monitor, and incorporate it as part of the system's "health-check" code (how many engineers would do this?) ¡£ The stack monitor will create a buffer area between the stack and the "other" memory area, and fill it with known bit patterns. Then the monitor will continuously monitor whether there are any changes in the pattern. If the bit pattern changes, it means that the stack has grown too large and is about to push the system into the dark abyss! At this point, the monitor can record the occurrence of events, the system status, and any other useful data, which can be used for problem diagnosis in the future.
Most real-time operating systems (RTOS) or microcontroller systems that implement memory protection units (MPU) all have stack monitors. The scary thing is that these functions are usually in a disabled state by default, or they are often deliberately turned off by developers. A quick search on the internet will reveal that many people recommend disabling the stack monitors in real-time operating systems to save 56 bytes of flash memory space, etc. But this is a losing proposition!