Detecting stack overflow

korggy wrote on Tuesday, January 22, 2008:

Is there a way port.c could be easily modified to detect an overflow of the stack area allocated for each task, probably during context switching? Perhaps it could do this in a “checked” build and trigger a reset or an assertion of some other kind. At the moment, it’s difficult to predict/detect such software stack overflows unless I observe that my system starts behaving strangely and then spend a lot of time isolating the problem.

rtel wrote on Tuesday, January 22, 2008:

It is fairly straight forward to prevent the scheduler writing over the end of the task stack as it knows where the stack start and end are. 

It is a harder to *reliably* detect a task writing over the end of stack.  A common technique is to put some known values at the end of the stack, then have the scheduler check that the known values are still there before switching to the next task - but this does not guarantee you will catch the fault as it is possible to write beyond the marker bytes without writing over the market bytes themselves.