# FreeRTOS：在prvCheckHeap()第234行检测到堆损坏

- **ID:** `embedded/rtos-heap-corruption`
- **领域:** embedded
- **类别:** runtime_error
- **验证级别:** ai_generated
- **修复率:** 72%

## 根因

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

## 版本兼容性

| 版本 | 状态 | 引入 | 弃用 |
|------|------|------|------|
| FreeRTOSv202212.01 | active | — | — |
| STM32Cube_FW_F4_V1.27.0 | active | — | — |
| ARM GCC 12.2.1 | active | — | — |

## 解决方案

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.
   ```

## 无效尝试

- **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% 失败率)
- **Adding assert() statements around every malloc/free call** — Asserts only halt execution; they do not prevent corruption and may mask intermittent issues. (80% 失败率)
- **Switching to heap_4.c from heap_2.c** — Different heap implementation may change behavior but cannot fix logical errors like double free. (85% 失败率)
