Memory leak in Ethernet.cpp - Arduino 1.0.1

Hello, I am working on some arduino based device and I probably found potentionaly memory leak in Ethernet.cpp.

When I use Ethernet.begin(mac) which is designed for starting ethernet with DHCP and I have not ethernet cable in ethernet connector (intentionally for reasons of testing unavailable network), the DHCP sets IP, GW, Mask and DNS to New function Ethernet.maintain()which comes with Arduino libraries 1.0.1, does not set network IP, GW, Mask, DNS, even if DHCP is OK and network is reachable again. I need something like restart ethernet after i detect, that network is unavailable, so I call Ethernet.begin(mac) again after few minutes fot testing, if network is reachable.

But… in Ethernet.cpp, there is new alocation of private property _dhcp and it causes the memory leak.

I patch it simply by

int EthernetClass::begin(uint8_t *mac_address)                                                                                                                                                                    
if(_dhcp == NULL)   // <--- DHCP not alocated ?                                                                                                                                                                                  
   _dhcp = new DhcpClass();  


But in original code there is not any control. Possibility is release old _dhcp if it is not NULL.

Is there any way to do Ethernet restart better than repeatedly calling Ethernet.begin, causing a new allocation of _dhcp property?

Thanks for reply and sorry for my bad english, I am not english speaker. Still learning English :slight_smile:

Looks like you are right. Or you could do:

  delete _dhcp;
  _dhcp = new DhcpClass();

Your method probably avoids memory leaks.

Would you call begin() more than once?

Would you call begin() more than once?

Yes. I must. begin() works fine, network is restarted well on the fly. I am trying maintain() to avoid calling begin() more than once, but when I test it, maintain() does not set network from DHCP, if it is not set by first call of begin(). I also considered own implementation of Ethernet.begin() functionality (something like MyEthernetBegin() :) ) because of doing no changes in oficial library, but I'd rather use the official library. The patch was simplest way to use oficial library. But now I must remember it, when Arduino team release new library without the patch. :)

Bug report submitted: