Possible to detect stack overrun?

cancel
Showing results for 
Show  only  | Search instead for 
Did you mean: 

Possible to detect stack overrun?

438 Views
lpcware
NXP Employee
NXP Employee
Content originally posted in LPCWare by stuartreynolds on Thu Apr 05 10:31:53 MST 2012
I'm getting some flaky behavior in a program when I increase a buffer size to cause my binary to closely fit what's available on my uC's (LPC1313).
I have a theory that the stack overflows and is causing memory corruption. Is there a way to test this? (e.g. set a value at highest allowable stack location and check it periodically, or during a crash).

Regards,
- Stu
0 Kudos
1 Reply

291 Views
lpcware
NXP Employee
NXP Employee
Content originally posted in LPCWare by Rob65 on Fri Apr 06 08:59:19 MST 2012
That's no problem at all.
But I'm not going to type this out completely - you'll have to do some work for this yourself ;)

Have a look at cr_startup_lpc13.c and also look at the Xpresso1343_usb_serial_debug.ld file (in the Debug folder after you compiled your app. at least once in debug mode).

At the end of the debug.ld file you'll find two lines with a PROVIDE statement. This creates the labels _pvHeapStart and _vStackTop.
_pvHeapStart is at the end of all allocated data (both pre-initialized and BSS) and _vStackTop is at the top of your memory (where the stack starts).
The stack grows down toward your .bss segment so your memory is filled from top to bottom by the stack usage.

now it is time to look at the cr_startup file and search for the ResetISR() function. In there two functions are being called: data_init() and bss_init(). These functions copy you pre-initialized (global) data from Flash to RAM and bss_init() clears your bss (resets all vars to 0).
You can make an extra function to place some magic constant (like 0xabbababe) in the segment between _pvHeapStart and _vStackTop - just make sure that you leave some words free since the stack is already being used (something like 128 bytes should be more than enough).

Now, when your program runs (or crashes) check the content of your stack.

Good hunting!
[INDENT]Rob
[/INDENT]
0 Kudos