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);