I am trying to concatenate an Arduino String and a const string. It causing random characters as a result. Have you encountered a problem like this?
Thanks
String mac2String(byte ar[])
{
String s;
for (byte i = 0; i < 6; ++i)
{
char buf[3];
sprintf(buf, "%02X", ar[i]); // J-M-L: slight modification, added the 0 in the format for padding
s += buf;
if (i < 5)
s += ':';
}
return s;
}
uint64_t chipid = ESP.getEfuseMac();
topic = mac2String((byte *)&chipid) + "/hello";
Serial.println("now subscribing: " + topic);
I'm not seeing any problems with your code, appears to print properly here. With Strings, I'd suspect a memory corruption problem, particularly if your sketch is low on available ram to begin with.
With "MQTT" visible in the output, where only hex digits and colons would be expected, does indicate some corruption.
If declaring char buf[3] as static char buf[3] makes the problem appear to go away, then a RAM problem is very plausible.
I'm not used to using String, does the compiler actually return a String from the function, or a reference to the local variable that goes out of scope?
david_2018:
I'm not used to using String, does the compiler actually return a String from the function, or a reference to the local variable that goes out of scope?
The local String s is effectively preserved because the return statement assigns the String back to the function.
It would be different if, within the function, the user built up a local String s, then assigned s.c_str (or something similar) to a global variable. Once the function ends, any global variables left pointing at (non static) variables, local to that function, will be in an undefined state.