This thread has been locked.

If you have a related question, please click the "Ask a related question" button in the top right corner. The newly created question will be automatically linked to this question.

Possible memory Leak in lwIP port

I am using lwIP  on an rm46 to communicate over UDP and am sending/receiving relatively small packets (~100 bytes) at a 1kHz rate. After 5+ minutes of sending and receiving UDP traffic pbuf_alloc(PBUF_TRANSPORT,(u16_t)pktSize,PBUF_POOL) starts returning NULL. Meaning it is unable to allocate a buffer for transmission. Which it is unable to do so because there are no pbufs available in the pbuf pool because a pbuf is not being properly freed somewhere. In my hunt for the unfreed pbuf I found "pbuf_free((struct pbuf *)curr_bd->pbuf);" in hdkif_tx_inthandler(struct netif *netif) of lwip-1.4.1/lwip/ports/hdk/netif/hdkif.c without the return value being checked. I have been using lwIP on the Hercules for about a year now and it is not uncommon for pbuf_free() to not free the pbuf and return a 0. Meaning pbuf_free() should be wrapped in a loop like so:

//Free the lwip buffer.
int freeTimeout = 100;
u8_t numFreed = 0;
do
{
numFreed = pbuf_free((struct pbuf *)curr_bd->pbuf);
--freeTimeout;
} while(numFreed <= 0 && freeTimeout >= 0);

In this particular spot however it is VERY common for pbuf_free to not free curr_bd->pbuf. When I looked into it, it is because for some reason curr_bd->pbuf->ref is equal to 0! And when pbuf_free is called it decrements the reference count... which is an unsigned 16 bit value meaning the reference count ends up being 65,535.  

Somehow this ends up working most of the time because I only get this issue when the Hercules is under load. Otherwise the UDP rx/tx and run overnight and transfers nearly a billion packets with no problem.

I am wondering what is going on and why the reference count for the pbuf in that function is 0... I'd like to know what is going on as i search for my memory leak. Sadly putting the loop i posted above in that location didn't fix the issue but i need to know if i should keep that loop in place or not.