String concat (+) problem

Hi,

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

and the outputs look like:
Screenshot 2020-11-20 140913.jpg

Screenshot 2020-11-20 140913.jpg

I guess topic is defined as a String.
I'd try instead of this:

s += buf ;

this :

s += String( buf ) ;

and also set s explicitly to "" with String s = "" ;

Also, look at snprintf() instead of sprintf(). It is generally safer.

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.

you shouldn't use String on a microcontroller at all. Microcontrollers are low on RAM

This is the reason why

c++ is a very famous programming-language. But it has its flaws and "bugs" if you don't know much about it

Use the library PString or SafeStrings instead

best regards Stefan