# lwIP: mem_malloc failed: PBUF_POOL exhausted

- **ID:** `embedded/lwip-memory-pool-exhaustion`
- **Domain:** embedded
- **Category:** resource_error
- **Verification:** ai_generated
- **Fix Rate:** 78%

## Root Cause

The lwIP TCP/IP stack's PBUF pool is depleted due to excessive packet allocation without timely freeing, often from a burst of incoming data or a memory leak in the application.

## Version Compatibility

| Version | Status | Introduced | Deprecated |
|---------|--------|------------|------------|
| lwIP 2.1.2 | active | — | — |
| lwIP 2.0.3 | active | — | — |
| FreeRTOS+TCP 2.0.0 | active | — | — |

## Workarounds

1. **Increase PBUF_POOL_SIZE and PBUF_POOL_BUFSIZE in lwipopts.h. For example:
#define PBUF_POOL_SIZE 20
#define PBUF_POOL_BUFSIZE 1518** (70% success)
   ```
   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; }** (80% success)
   ```
   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.** (90% success)
   ```
   Use memory profiling with lwIP's stats API (lwip_stats.mem.used) to identify the real bottleneck and adjust pool sizes accordingly.
   ```

## Dead Ends

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