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

- **ID:** `embedded/rtos-heap-corruption`
- **Domain:** embedded
- **Category:** runtime_error
- **Verification:** ai_generated
- **Fix Rate:** 72%

## Root Cause

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

## Version Compatibility

| Version | Status | Introduced | Deprecated |
|---------|--------|------------|------------|
| FreeRTOSv202212.01 | active | — | — |
| STM32Cube_FW_F4_V1.27.0 | active | — | — |
| ARM GCC 12.2.1 | active | — | — |

## Workarounds

1. **Enable heap monitoring by setting configUSE_MALLOC_FAILED_HOOK to 1 and implementing vApplicationMallocFailedHook() to log the task name and stack trace.** (70% success)
   ```
   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;** (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;
   ```
3. **Add memory guard words before and each allocated block: #define GUARD 0xDEADBEEF; and check them after free to detect buffer overflow.** (75% success)
   ```
   Add memory guard words before and each allocated block: #define GUARD 0xDEADBEEF; and check them after free to detect buffer overflow.
   ```

## Dead Ends

- **Increasing total heap size in FreeRTOSConfig.h (configTOTAL_HEAP_SIZE)** — Larger heap only delays corruption detection; does not fix the root cause of memory mismanagement. (90% fail)
- **Adding assert() statements around every malloc/free call** — Asserts only halt execution; they do not prevent corruption and may mask intermittent issues. (80% fail)
- **Switching to heap_4.c from heap_2.c** — Different heap implementation may change behavior but cannot fix logical errors like double free. (85% fail)
