For many embedded developers, the stack seems to be a rather mysterious force. When strange things start to happen, the engineers are finally stumped, and they start thinking that maybe something is going on in the stack. The result is mindlessly adjusting the size and position of the stack, and so on. But the error is often stack independent, but how can you be so sure? After all, how many engineers have actually performed a worst-case stack size analysis?
The stack size is statically allocated at compile time, but the stack is used dynamically. As the code executes, variables, return addresses, and other information required by the application are continuously stored on the stack. This mechanism causes the stack to grow in the memory it allocates. However, this growth can sometimes exceed the capacity limits determined at compile time, causing the stack to corrupt data in adjacent memory regions.
One way to absolutely ensure that the stack is working properly is to implement a stack monitor as part of your system's "health" code (how many engineers do that?). . The stack monitor creates a buffer area between the stack and the "other" memory area and populates it with known bit patterns. The monitor will then constantly monitor the pattern for any changes. If the bit pattern changes, it means that the stack has grown too large and is about to push the system into the dark hell! At this point, the monitor can record the occurrence of events, the state of the system, and any other useful data for later diagnosis of the problem.
Stack monitors are available in most real-time operating systems (RTOS) or microcontroller systems that implement a memory protection unit (MPU). The scary thing is that these features are turned off by default, or are often intentionally turned off by developers. A quick search on the web reveals that many people recommend turning off the stack monitor in the real-time operating system to save 56 bytes of flash memory space, etc., which is not worth the cost!