intelligently avoiding a fatal stack overflow crash?

societyofrobots
Posts: 13
Joined: Fri Oct 02, 2020 9:32 pm

intelligently avoiding a fatal stack overflow crash?

Postby societyofrobots » Sun Sep 19, 2021 1:12 am

I have a file, X, that logs events and is stored in SPIFFS.

Once every few months, X fills up SPIFFS. When that happens, my software prunes older data from the log.

To do this, I:
- create String S
- copy only the newer half of file X into string S
- dump S into a new file, Y
- then I delete X, using Y as the new log

This code is working great for me, but...

I am concerned that one day for unforeseen reasons my available memory (stack?) could be less than the size of S. Boom, overflow.

Is there a way to ensure S won't overflow the stack? Could I check for free memory, thereby limiting data into S?

I could just appendFile(), byte by byte, from X to Y, without using S. But...

I also serve S in a webpage for users to view the log:

Code: Select all

server.send(200, "text/html", S);
Any advice? I'm not the most skilled of programmers, so dumb it down for me!

WiFive
Posts: 3529
Joined: Tue Dec 01, 2015 7:35 am

Re: intelligently avoiding a fatal stack overflow crash?

Postby WiFive » Sun Sep 19, 2021 4:02 am

Is there a way to ensure S won't overflow the stack?
Yes, don't put S in the stack. Put it in the heap and make sure you don't write more than its size.
I also serve S in a webpage for users to view the log:
Plenty of web server examples that can serve files from spiffs.

societyofrobots
Posts: 13
Joined: Fri Oct 02, 2020 9:32 pm

Re: intelligently avoiding a fatal stack overflow crash?

Postby societyofrobots » Sun Sep 19, 2021 11:57 pm

don't put S in the stack. Put it in the heap and make sure you don't write more than its size.
How do I control whether S is put in the stack or heap?
Plenty of web server examples that can serve files from spiffs.
Thanks I'll look into it.

Some code I figured out which should be 'good enough' to make sure S will be smaller than the available heap...

Code: Select all

if(file.size() > ESP.getMaxAllocHeap()-10000)
   prune();

Who is online

Users browsing this forum: Baidu [Spider] and 77 guests