embedded resource_error ai_generated true

lwIP: mem_malloc failed: PBUF_POOL exhausted

ID: embedded/lwip-memory-pool-exhaustion

Also available as: JSON · Markdown · 中文
78%Fix Rate
85%Confidence
1Evidence
2023-06-15First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
lwIP 2.1.2 active
lwIP 2.0.3 active
FreeRTOS+TCP 2.0.0 active

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.

generic

中文

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

Official Documentation

https://www.nongnu.org/lwip/2_1_x/group__pbuf.html

Workarounds

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

中文步骤

  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.

Dead Ends

Common approaches that don't work:

  1. 60% fail

    Increasing PBUF_POOL_SIZE in lwipopts.h without analyzing actual usage often masks the underlying issue, causing out-of-memory elsewhere.

  2. 40% fail

    Setting PBUF_POOL_SIZE to a very large value may exhaust heap memory, leading to system crashes or HardFaults.

  3. 30% fail

    Adding more debug prints in the packet processing path can increase memory pressure and worsen the exhaustion.