Electronic – How to check for Stack overflow in an embedded application


I have run into a problem where I believe my stack is overflowing. The reason I am inclined to think this way, is due to the following:

1) Compile code, dump into the device: – no activity from the device (I am expecting an 'I am alive' message)
2) In this situation, I increased the stack size by 10 bytes, recompiled and dumped to the device, and the problem went away.
3) Tried the above two steps 10 times, back and forth, and can reproduce the problem reliably, and fix it reliably.

I want to see the stack falling over, how do I do this?

I am currently using an M16 Microcontroller, with 2K RAM (30 bytes left), 256 Bytes Stack size.
The IAR Workbench that I am using, does not have the call graph utility.

Are there other ways to do this – check the stack falling over and by how much in code?

Any help will really be appreciated.


Best Answer

A common way to check for memory usage is to prefill memory with a constant value before your program runs. eg a sequence of 0xde 0xad could be written out to your stack area by your startup code. During the program's operation, the stack will grow and write over these sequences. If you then have the ability to examine memory, then you can easily see the untouched 0xde 0xad bytes in memory and so determine how much stack has been used.

It's usually hard to detect an overflow as it occurs since function call return addresses are stored on the stack and any function return will send the program off into the weeds. In this case, if your watchdog is enabled and you can set a breakpoint at the reset vector, you may still be able to examine the memory and look for your prefill bytes to determine if this is what has caused a reset.