# lwIP：memp_malloc 失败：PBUF_POOL 耗尽

- **ID:** `embedded/lwip-memp-pbuf-pool-exhausted`
- **领域:** embedded
- **类别:** resource_error
- **错误码:** `MEM_ERR_MEM`
- **验证级别:** ai_generated
- **修复率:** 81%

## 根因

lwIP pbuf 池（PBUF_POOL）由于网络流量峰值、数据包处理中的内存泄漏或 lwipopts.h 中池大小配置不足而耗尽空闲缓冲区。

## 版本兼容性

| 版本 | 状态 | 引入 | 弃用 |
|------|------|------|------|
| lwIP v2.1.3 | active | — | — |
| FreeRTOS v10.4.6 | active | — | — |
| STM32Cube_FW_F7 v1.17.0 | active | — | — |

## 解决方案

1. ```
   使用周期性任务监控 pbuf 池使用情况：调用 memp_stats() 并记录空闲 pbuf 数量；如果低于阈值，通过 tcp_abort() 强制释放旧连接。
   ```
2. ```
   在 lwipopts.h 中增加 PBUF_POOL_SIZE 和 PBUF_POOL_BUFSIZE：设置 PBUF_POOL_SIZE 为 50，PBUF_POOL_BUFSIZE 为 1524，以处理最大以太网帧。
   ```
3. ```
   实现 pbuf 泄漏检测：使用计数器包装 pbuf_alloc() 和 pbuf_free()，当空闲计数低于池大小的 10% 时记录堆栈跟踪。
   ```

## 无效尝试

- **Increase PBUF_POOL_SIZE to a very large value (e.g., 1000)** — Large pools consume excessive RAM; memory exhaustion may cause system instability without fixing the leak. (70% 失败率)
- **Disable TCP window scaling to reduce buffer usage** — TCP performance degrades significantly, and the issue may persist if the leak is in UDP or raw packets. (85% 失败率)
- **Use dynamic pbuf allocation (PBUF_RAM) instead of pool** — Dynamic allocation can fragment heap and cause out-of-memory errors, especially in constrained systems. (80% 失败率)
