embedded runtime_error ai_generated true

FreeRTOS: heap corruption detected in prvCheckHeap() at line 234

ID: embedded/rtos-heap-corruption

Also available as: JSON · Markdown · 中文
72%Fix Rate
88%Confidence
1Evidence
2024-01-05First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
FreeRTOSv202212.01 active
STM32Cube_FW_F4_V1.27.0 active
ARM GCC 12.2.1 active

Root Cause

Memory corruption caused by buffer overflow, double free, or use-after-free in heap-allocated objects.

generic

中文

内存损坏由缓冲区溢出、重复释放或释放后使用堆分配对象引起。

Official Documentation

https://www.freertos.org/Documentation/02-Kernel/02-Kernel-features/03-Memory-management/01-Memory-management

Workarounds

  1. 70% success Enable heap monitoring by setting configUSE_MALLOC_FAILED_HOOK to 1 and implementing vApplicationMallocFailedHook() to log the task name and stack trace.
    Enable heap monitoring by setting configUSE_MALLOC_FAILED_HOOK to 1 and implementing vApplicationMallocFailedHook() to log the task name and stack trace.
  2. 90% success Use static allocation for all tasks and queues: replace pvPortMalloc() with static buffers defined at compile time, e.g., StackType_t taskStack[256]; StaticTask_t taskBuffer;
    Use static allocation for all tasks and queues: replace pvPortMalloc() with static buffers defined at compile time, e.g., StackType_t taskStack[256]; StaticTask_t taskBuffer;
  3. 75% success Add memory guard words before and each allocated block: #define GUARD 0xDEADBEEF; and check them after free to detect buffer overflow.
    Add memory guard words before and each allocated block: #define GUARD 0xDEADBEEF; and check them after free to detect buffer overflow.

中文步骤

  1. Enable heap monitoring by setting configUSE_MALLOC_FAILED_HOOK to 1 and implementing vApplicationMallocFailedHook() to log the task name and stack trace.
  2. Use static allocation for all tasks and queues: replace pvPortMalloc() with static buffers defined at compile time, e.g., StackType_t taskStack[256]; StaticTask_t taskBuffer;
  3. Add memory guard words before and each allocated block: #define GUARD 0xDEADBEEF; and check them after free to detect buffer overflow.

Dead Ends

Common approaches that don't work:

  1. Increasing total heap size in FreeRTOSConfig.h (configTOTAL_HEAP_SIZE) 90% fail

    Larger heap only delays corruption detection; does not fix the root cause of memory mismanagement.

  2. Adding assert() statements around every malloc/free call 80% fail

    Asserts only halt execution; they do not prevent corruption and may mask intermittent issues.

  3. Switching to heap_4.c from heap_2.c 85% fail

    Different heap implementation may change behavior but cannot fix logical errors like double free.