Can't return a String

Ubuntu
Arduino IDE
ESP32

Simple, simple, simple... All I want to do is return a String (big S) from a function. Here is the simplest program that demonstrates the problem. I have been working on this simple problem for several hours over 2 days! I have seen a hundred different explanations (and tried ALL of them) and suggestions.

Why is it so difficult to convert the macStr[18] to a String and return it?

Thank you for your help.

Here is the output:

15:26:47.025 -> MAC2STR(): 00:B8:15:D8:D8:1C
15:26:47.058 -> MAC2STR: 8⸮⸮?

And here is the entire sketch.

String MacToStr(char *mac)
{
  char macStr[18];

  snprintf(macStr, sizeof(macStr), "%02X:%02X:%02X:%02X:%02X:%02X",
         mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]);
  printf("MAC2STR(): %s\n", macStr);
  return String(macStr);
}

void setup() 
{
  // put your setup code here, to run once:
  Serial.begin(115200);
  
  char buf[6] = {0x0, 0xb8, 0x15, 0xd8, 0xd8, 0x1c};

  String myStr = MacToStr(buf);
  
  printf("MAC2STR: %s\n", myStr);
}

void loop() {
  // put your main code here, to run repeatedly:

}

maybe

String MacToStr(char *mac)
{
  static String retString;
  char macStr[18];

  snprintf(macStr, sizeof(macStr), "%02X:%02X:%02X:%02X:%02X:%02X",
         mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]);
  printf("MAC2STR(): %s\n", macStr);
  retString = String(macStr);
  return retString;
}

untested, honestly I'm not sure if you can get away with declaring an object static. Generally, what is happening is that all dynamic data is de-allocated when you return from a function. So if you return an object referenced in a function, it may not exist.

I’ve been too lazy to test that out, but it may just as well be declared global… uses the same amount of memory.

Me too. Or, I would just not use String at all, make the char array static and deal with char arrays exclusively. Return a pointer to the char array instead.

There probably is a "right" way to do it, this is at the edge of my expertise.

Thank you for the replies. I actually discovered the problem 30 minutes after I made this post.

By way of explanation: 0xD8 is 216 dec. That is to big to fit in a signed char. I changed my hex array (buf) to unsigned char

unsigned char buf[6] = {0x0, 0xb8, 0x15, 0xd8, 0xd8, 0x1c};

as well as the signature for

MacToStr(unsigned char *mac).

I was overflowing the buf and stomped on some memory somewhere which explains the garbage in the output. If the program had just crashed it probably would have been easier to figure out, lol!

2 Days!

But right as rain now. (who said that? :slightly_smiling_face: )

Thanks again good people!
Slava Ukraine!

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.