I'm having some issues dealing with strings in a small Arduino app. I wonder why this code works:

mqtt.setServer("", port);

and this code doesn't:

IPAddress ip = MDNS.queryHost(...);
mqtt.setServer(ip.toString().c_str(), port);

Even when strcmp returns 0 when I compare both:

strcmp(ip.toString().c_str(), ""); // output = 0 => equality

I've also tried other alternatives, such as creating a char array, with no luck:

String ipstr = ip.toString();
char ipchar[ipstr.length() + 1];
ipstr.toCharArray(ipchar, ipstr.length() + 1);

mqtt.setServer(ipchar, port);

All alternatives compile, but the mqtt connection is never established later on. I must be missing something obvious because it works when I hardcode the "" string.

  • 4
    What does the mqtt.setServer do? Does it store a pointer reference or does it copy the input string to its own buffers? If you use a constant "" then that string will be static. WHen you use ip.toString().c_str(), when the ip object is deallocated but .setServer() still has a reference to that char*, it's become invalid. Where is the library you're using? Jun 3, 2018 at 15:11

1 Answer 1


PubSubClient::setServer(const char * domain, uint16_t port) just saves the pointer, it doesn't copy the string (probably because it expects a static string literal). (Source)
In your case, when ip goes out of scope, the pointer is no longer valid, so it won't work.

Just use the PubSubClient::setServer(IPAddress ip, uint16_t port) function instead. (Source)

Always read the API documentation, most libraries have one, even though it can be hard to find. The ReadMe and GitHub Wiki pages are a good place to start.
If that's insufficient (not uncommon for open source projects), read the header files, which list all functions of the library.
If you still have doubts about what a function does, refer to the actual implementation files.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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