Receiving garbled `char` array returned by a function
It's because you're returning a pointer to a local variable.

You are only returning the address in memory where your char array is allocated. That allocation is on the stack and only exists for the lifetime of the function.  But you still have the address where that memory was allocated, and you're using it as if it's still allocated.

When you append it to a String room is allocated on the heap and the data is copied in. That heap allocation remains until the String object is destroyed, either by going out of scope or by you manually destroying it.

It's pure chance that the data is still available and intact at the point of copying.

In short:


You must never return a pointer to a locally allocated (non-static) array.


Things you can do that are correct:


Pass an array pointer to the function to be populated by the function
Return a pointer to a statically allocated local array
Return a String object (though I wouldn't recommend using String for anything)


My preferred method is the first, whereby you define an array in the outer scope, then pass that (and possibly the array length) to the function. The function then populates the array it has been passed.  This also has the advantage that the function can use the return value to indicate a status or other quantity.

For example:

void myFunc(char *buf, int len) {
    for (int i = 0; i &lt; len - 1; i++) {
        buf[i] = 'A';
    }
    buf[len - 1] = 0;
}

char myBuf[20];
myFunc(myBuf, 20);
Serial.println(myBuf);

--&gt; AAAAAAAAAAAAAAAAAAAA