0
0
Power-electronicsDebug / FixBeginner · 4 min read

How to Avoid Stack Overflow in Embedded C: Causes and Fixes

To avoid stack overflow in embedded C, limit deep or infinite recursion and large local variables on the stack. Use iterative approaches and allocate big data structures in static or heap memory instead of the stack.
🔍

Why This Happens

Stack overflow happens when a program uses more stack memory than is available. This often occurs due to deep or infinite recursion or declaring very large local variables inside functions. The stack is a small, fixed-size memory area for function calls and local data, so exceeding it causes the program to crash or behave unpredictably.

c
#include <stdio.h>

void recursive_function() {
    int large_array[10000]; // Large local array uses lots of stack
    printf("Calling recursive_function\n");
    recursive_function(); // Infinite recursion causes stack overflow
}

int main() {
    recursive_function();
    return 0;
}
Output
Stack overflow error or program crash due to infinite recursion and large stack usage
🔧

The Fix

To fix stack overflow, avoid infinite recursion and reduce stack memory usage. Replace recursion with loops when possible and move large arrays to static or global memory. This keeps the stack small and prevents overflow.

c
#include <stdio.h>

void iterative_function() {
    static int large_array[10000]; // Static array stored outside stack
    for (int i = 0; i < 10; i++) {
        printf("Iteration %d\n", i);
    }
}

int main() {
    iterative_function();
    return 0;
}
Output
Iteration 0 Iteration 1 Iteration 2 Iteration 3 Iteration 4 Iteration 5 Iteration 6 Iteration 7 Iteration 8 Iteration 9
🛡️

Prevention

To prevent stack overflow in embedded C:

  • Limit recursion depth or avoid recursion entirely.
  • Use static or global variables for large data instead of local variables.
  • Check stack size limits for your embedded system and configure your build accordingly.
  • Use tools or static analyzers to detect potential stack overflows.
  • Write iterative code where possible to control memory use.
⚠️

Related Errors

Similar errors include:

  • Heap overflow: Happens when dynamic memory allocation exceeds available heap space.
  • Memory corruption: Caused by writing outside allocated memory, often due to stack overflow.
  • Watchdog resets: Caused by infinite loops or crashes from stack overflow in embedded systems.

Key Takeaways

Avoid deep or infinite recursion to prevent stack overflow.
Use static or global memory for large data instead of stack variables.
Replace recursion with iteration when possible.
Check and configure stack size limits for your embedded system.
Use static analysis tools to detect stack usage issues early.