1

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

mqtt.setServer("192.168.1.42", 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(), "192.168.1.42"); // 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 "192.168.1.42" string.

  • 3
    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 "192.168.1.42" 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? – Maximilian Gerhardt Jun 3 '18 at 15:11
6

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, privacy policy and cookie policy

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