0

I am experiencing some problems with string in Arduino application with ESP32. I don't understand why this code works:

mqtt.setServer ("m20.cloudmqtt.com", port); //is OK

and this does not work does not connect

String strSBM = "m20.cloudmqtt.com"; mqtt.setServer (strSBM.c_str (), port); //no OK

I use library PubSubClient 2.7

Any of you can help me

Many thanks

0

When you set the server from a C string it doesn't copy the string - it just retains a pointer to it:

PubSubClient& PubSubClient::setServer(const char * domain, uint16_t port) {
    this->domain = domain;
    this->port = port;
    return *this;
}

If the string it's pointing to goes out of scope (it's a local variable and the function finishes) the data for the string will be invalidated and lost.

It is really intended to work with string literals and global constant variables that never change.

If this is the one and only time that you ever set the server you could get away with using strdup() to duplicate the string data on the heap, but without direct access to the domain member variable of the PubSubClient class you have no way to free() the memory again should you ever wish to change the server.

String strSBM = "m20.cloudmqtt.com";
mqtt.setServer (strdup(strSBM.c_str()), port); 

To make it so you can free the value you need to keep track of it separately:

static char *temp = NULL;
if (temp != NULL) {
    free(temp);
    temp = NULL;
}
temp = strdup(strSBM.c_str());
mqtt.setServer(temp, port);
  • same problem for the port number what function should i use for the port? Thanks for your help – Michele Aug 14 '19 at 11:37
  • No, not the same problem for the port number - that's just a number and gets copied. The problem only exists for the server name because that is a pointer. – Majenko Aug 14 '19 at 11:46
  • Ok now everything seems to work with client.setServer (strdup (strSBM.c_str ()), (int) strPSBM.toInt ()); – Michele Aug 14 '19 at 11:56
  • As long as you only ever do that once it's fine - if you do it more than once you have created a memory leak and you will crash after a while. Why exactly do you want the server name in a String though? – Majenko Aug 14 '19 at 12:08
  • Ohh, then this is not good for me, because in my project I save the name of the server and number port to an external EEPROM and I have the possibility to change the configuration parameters. So having static parameters is not good. Do you have any suggestions? – Michele Aug 14 '19 at 13:19

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.