Memory-Safe Applications on Teensy 4.0

njanks

New member
I've decided to use the Teensy 4.0 on some projects of mine. I have been advised to not use standard arduino and platformio libraries because they use dynamic memory allocation in the background, which can lead to memory fragmentation and crashes. Is there some way I can get around this? Can I force arduino + platformio libraries to only use static memory, or would I have to write something purely in C? I'm just looking for the best way to make sure long-running applications have little to no chance of crashes.
 
I've decided to use the Teensy 4.0 on some projects of mine. I have been advised to not use standard arduino and platformio libraries because they use dynamic memory allocation in the background, which can lead to memory fragmentation and crashes. Is there some way I can get around this? Can I force arduino + platformio libraries to only use static memory, or would I have to write something purely in C? I'm just looking for the best way to make sure long-running applications have little to no chance of crashes.
You can use Arduino and C++ and avoid any dynamic memory allocation. How easy or hard that is will depend on what you’re trying to do, and what libraries you might want to use. Can’t say more unless you share what you’re trying to do. It would not be trivial at all to try to use T4.0 and write everything from scratch.
 
what libraries you might want to use
Some drivers may use C++ allocation or other dynamic memory, but even so it should be designed to be stable.
The Teensy and PJRC code itself is mostly C/asm and doesn't do much dynamic allocation but does offer a useful set of dynamic allocation tools as needed for responsible use.
 
Some drivers may use C++ allocation or other dynamic memory, but even so it should be designed to be stable.
The Teensy and PJRC code itself is mostly C/asm and doesn't do much dynamic allocation but does offer a useful set of dynamic allocation tools as needed for responsible use.
Good points. No need to worry about one-time dynamic allocation of objects. Just avoid repeated allocation and deallocation.
 
Simple rule to stable memory is never call free() or use delete, and never allocate after initialization - basically pre-allocate everything. But dynamic memory allocation can be stable, so long as the amount of live data is small compared to what's available - most allocation schemes can tolerate fragmentation in this regime - there are simply so many free objects compared to allocated objects that coallescing free blocks works well.

But on a very resource constrained system like an ATmega328 static allocation only is the best approach, then the compiler can tell you it won't work.

You also have to bound the stack size of course...
 
Back
Top