Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Find Stack Overflow in Microcontrollers using C in Run Time

I am creating the application on STM32 microcontroller. I am using some library stack. Above that stack, I am using my application. I have two questions:

  1. How can I detect and handle the stack over flow in runtime. Because I don't know how much memory that library is using.

  2. How can I detect and handle the stack over flow in runtime if I am developing the code from the scratch. I read some where we have to maintain some count for each declaration. Is this correct way or any standard way to find it.

like image 499
Reshmi khanna Avatar asked Sep 19 '25 16:09

Reshmi khanna


1 Answers

if you are limited to your device and no "high sophisticated" tools available, you could at least try "the old way". A simple stack guard may help. Somewhere in your code (depends on the tools you use), there must be the definition of the stack area. Something similar to:

.equ         stacksize, 1024

stack:       .space   stacksize,0

(gnu as syntax, your's might be different)

with your device's startup code somewhere initializing the stack register to the top address of the stack area.

A stack guard would then just add a "magic number" to the stack top and bottom:

.equ         stackmagic,0xaffeaffe
.equ         stacksize, 1024


stacktop:    .int     stackmagic
stack:       .space   stacksize,0
stackbottom: .int     stackmagic

with some code at least periodically checking (e.g. in a timer interrupt routine or - if available - in your debugger) if the stackmagic values are still there.

like image 119
mfro Avatar answered Sep 22 '25 09:09

mfro