ArduinoHannover / ESPMailer

SMTP Client for ESP8266
GNU General Public License v3.0
12 stars 7 forks source link

Memory leak #10

Open EddieGreen opened 6 years ago

EddieGreen commented 6 years ago

The ESPMailer.cpp 'send()' method does not free up buf, and leaks quite a bit more than its 100 bytes on each send. I've been working on clearing up these leaks both within this library and WiFiClient and WiFiClientSecure methods.

For WiFiClient and WiFiClientSecure These methods like being stopped, and while I haven't diagnosed which commands are effective, here is my belt-and-braces approach:

    WiFiClientSecure wifiClientSecure; // use WifiClientSecure for HTTPS, WifiClient if HTTP
    ...
    ...
    ...
    //Disconnect
    wifiClientSecure.flush(); // may not be required
    wifiClientSecure.stop();
    delay(1000); // may not be required
    yield(); // may not be required

I added this code to the following...

For EspMailer: in 'send()' I replaced each occurrence of return false; with:

{
    free(buf);
    return false;
}

Modified end of method:

if (do_debug >= 0)
{
    Serial.println("Email send complete");
}

free(buf);
_smtp.flush();
_smtp.stop();
delay(1000); // may not be required
return true;

In calling method One last thing, undocumented but defined in ~ESPMailer(), is the cleanup for all other variables added to the heap by the library. Add delete(espMailer); at end of send routine to free up these resources. The complete method is shown as example:

bool SendSmtpEmail(char* emailAddress)
{
    Serial.printf("Heap: %d\n", ESP.getFreeHeap());

    ESPMailer* espMailer = new ESPMailer();

    // DEBUG LEVELS:
    // -1 = muted
    // 0 = only errors
    // 1 = Client -> Server
    // 2 = Server -> Client
    // 3 = both

    espMailer->setDebugLevel(-1);
    espMailer->Host = "#####################";
    espMailer->SMTPAuth = true;
    espMailer->AuthType = LOGIN;
    espMailer->Username = ""#####################";
    espMailer->Password = ""#####################";
    espMailer->setFrom(senderEmailAddress, senderName);
    espMailer->setTimezone(0); //defaults to UTC
    espMailer->addAddress(emailAddress);
    //espMailer->addBCC("bcc@example.org");
    espMailer->Subject = "#####################";
    espMailer->isHTML(true);
    espMailer->Body = "<h3 style=\"color: red;\">" + "#####################"+ "</h3>";
    espMailer->AltBody = "#####################";

    Serial.println("Sending SMTP Mail");
    bool sendSuccess = espMailer->send();
    if (sendSuccess)
    {
        Serial.println("Send success!");
    }
    else
    {
        Serial.println("Send failed!");
    }

    delete(espMailer); // free up ESPMailer heap

    Serial.printf("Heap: %d\n", ESP.getFreeHeap());

    return sendSuccess;
}

Hope this will help anyone experiencing memory leaks. If there is a sexier way to do this I'd like to know.

gamelaster commented 6 years ago

Pull request would be nice!

EddieGreen commented 6 years ago

image