# lwIP：mem_malloc 失败：PBUF_POOL 耗尽

- **ID:** `embedded/lwip-memory-pool-exhaustion`
- **领域:** embedded
- **类别:** resource_error
- **验证级别:** ai_generated
- **修复率:** 78%

## 根因

lwIP TCP/IP 协议栈的 PBUF 池因数据包分配过多且未及时释放而耗尽，通常由突发输入数据或应用程序内存泄漏引起。

## 版本兼容性

| 版本 | 状态 | 引入 | 弃用 |
|------|------|------|------|
| lwIP 2.1.2 | active | — | — |
| lwIP 2.0.3 | active | — | — |
| FreeRTOS+TCP 2.0.0 | active | — | — |

## 解决方案

1. ```
   Increase PBUF_POOL_SIZE and PBUF_POOL_BUFSIZE in lwipopts.h. For example:
#define PBUF_POOL_SIZE 20
#define PBUF_POOL_BUFSIZE 1518
   ```
2. ```
   Implement a packet rate limiter in the network receive callback to drop excess packets. Example:
if (p->tot_len > MAX_PACKET_SIZE) { pbuf_free(p); return ERR_MEM; }
   ```
3. ```
   Use memory profiling with lwIP's stats API (lwip_stats.mem.used) to identify the real bottleneck and adjust pool sizes accordingly.
   ```

## 无效尝试

- **** — Increasing PBUF_POOL_SIZE in lwipopts.h without analyzing actual usage often masks the underlying issue, causing out-of-memory elsewhere. (60% 失败率)
- **** — Setting PBUF_POOL_SIZE to a very large value may exhaust heap memory, leading to system crashes or HardFaults. (40% 失败率)
- **** — Adding more debug prints in the packet processing path can increase memory pressure and worsen the exhaustion. (30% 失败率)
