Sphere
Log in Join
☆ 3

freertos task hardfaults after a few minutes, stack overflow?

STM32F103, FreeRTOS 10.5.1, three tasks - sensor read, UART logging, and a control loop. After 5-15 minutes the system hardfaults (HardFault_Handler). I enabled configCHECK_FOR_STACK_OVERFLOW = 2 and defined vApplicationStackOverflowHook, but the hook never fires - it just hardfaults. Tasks have 256-512 word stacks. Heap is 8KB. Could it be heap fragmentation from malloc in the UART task? I use sprintf into a local char[128] buffer in the logging task. Any way to catch this before it hardfaults?

⚑ Report

4 replies

☆ 0
G glitch ·2026-11-09#1

If the overflow hook never fires with method 2, it may not be a task stack overflow - could be heap corruption or an interrupt stack overflow. HardFault on F103 is often a bus fault from an invalid access. Implement a HardFault handler that dumps stacked PC/LR/R0-R3 (standard assembly stub) so you can see the faulting address. Also check heap with xPortGetMinimumEverFreeHeapSize. sprintf with a 128-byte buffer is fine if your format is bounded.

⚑ Report
☆ 0
V vector ·2026-11-11#2

Minimum ever free heap was around 400 bytes at one point, so tight but not zero. I added the hardfault dump and the stacked PC points into the logging task's sprintf call, LR near a vsnprintf-ish address. So it's in string formatting. But the buffer is 128 bytes and my strings are shorter than that. Could sprintf itself be recursing deeply and blowing the task stack?

⚑ Report
☆ 0
P plastic ·2026-11-12#3

Yes - newlib's sprintf/vsnprintf can use a surprising amount of stack, especially with floating-point conversions (%f), which pull in a lot of code and local state. A 256-word (1KB) task stack might not be enough if you're formatting floats. Either give the logging task a bigger stack (1024+ words) or avoid %f - pre-scale integers and print manually. Also make sure newlib has correct locking if tasks call printf concurrently.

⚑ Report
☆ 0
C cache ·2026-11-13#4

It was %f in sprintf on a 256-word stack. Bumped the logging task to 768 words and switched to printing integer millivolts instead of floats - no hardfault in 24 hours of testing. FreeRTOS stack overflow hook #2 didn't catch it because the corruption happened inside a library call and skipped the stack check. Moral: sprintf with floats is a stack hog on Cortex-M3, and don't trust the overflow hook to catch everything.

⚑ Report
Log in to reply.