By default, memory in DTCM (for Teensy 4.x) is ordered like this:
Initialized data -> Uninitialized data -> Stack
This means if there's a stack overflow, the uninitialized data can be silently corrupted. There's a 32 byte "no man's land" setup by the MPU to try to catch that happening, but it's not rare for a function with a lot of local variables to jump right over it without triggering the fault handler.
What can be done instead, is arranging the DTCM like this:
Stack -> Initialized data -> Uninitialized data
This way if the stack overflows, the stack pointer will definitely be pointing at an invalid memory address (below the beginning of DTCM) and trigger a fault. I managed to tweak the linker script for Teensy 4.1 to make this work:
github.com
I also removed the MPU section for the no man's land region, since it wasn't needed.
This does waste a little bit of space (4095 bytes max) since the Initialized data has to be aligned to a 4096 byte boundary for the static usb endpoint queue to function correctly.
Initialized data -> Uninitialized data -> Stack
This means if there's a stack overflow, the uninitialized data can be silently corrupted. There's a 32 byte "no man's land" setup by the MPU to try to catch that happening, but it's not rare for a function with a lot of local variables to jump right over it without triggering the fault handler.
What can be done instead, is arranging the DTCM like this:
Stack -> Initialized data -> Uninitialized data
This way if the stack overflows, the stack pointer will definitely be pointing at an invalid memory address (below the beginning of DTCM) and trigger a fault. I managed to tweak the linker script for Teensy 4.1 to make this work:
Teensy 4.1: move stack to beginning of DTCM · A-Dunstan/cores@9db2374
Teensy Core Libraries for Arduino. Contribute to A-Dunstan/cores development by creating an account on GitHub.
This does waste a little bit of space (4095 bytes max) since the Initialized data has to be aligned to a 4096 byte boundary for the static usb endpoint queue to function correctly.