Using MPLAB, I set a break point just before the call to OS_Delay(), which is just a macro to call OSDelay() and OS_Yield(), and observe the values of FSR0, 1 and 2. With MPLAB C compiler, FSR1 is the software stack pointer, and FSR2 is a frame pointer.

I change the break point to the try_counter-- statement, and when OS_Delay() returns, FSR1 and FSR2 have changed, and thus, variables local to the task are now bogus. Apparently, OS_Delay() changes FSR1 and FSR2, and does not restore them when returning to the main line code.

What am I doing wrong? I tried both sfc18sna.lib and sfc18sfa.lib (making the appropriate changes in salvocfg.h)

Because when the task reaches OS_Delay(), it context-switches. That means it unloads the stack, goes back to the scheduler (OSSched()), and becomes "dormant" until the delay expires. In the meantime, other tasks run and other functions are executed, all using the stack, and hence overwriting your on-stack local auto variables try_counter and state.

So, just make them static, since they need to persist across context switches.

Note that you can use non-static local auto variables inside tasks in places where persistence across context switches is not necessary ...