Returning String from a C function

My C is a bit rusty now, I’m try to refresh for hobby, so excuse me for a question that may be stupid to most people… so my question:

On those microcontroller is this piece of code safe? the massive use of String is it used in order to avoid the problem of longevity of data?

String getMacAddress() {
  uint8_t baseMac[6];
  char baseMacChr[13] = {0};
#  if defined(ESP8266)
  WiFi.macAddress(baseMac);
  sprintf(baseMacChr, "%02X%02X%02X%02X%02X%02X", baseMac[0], baseMac[1], baseMac[2], baseMac[3], baseMac[4], baseMac[5]);
#  elif defined(ESP32)
  esp_read_mac(baseMac, ESP_MAC_WIFI_STA);
  sprintf(baseMacChr, "%02X%02X%02X%02X%02X%02X", baseMac[0], baseMac[1], baseMac[2], baseMac[3], baseMac[4], baseMac[5]);
#  else
  sprintf(baseMacChr, "%02X%02X%02X%02X%02X%02X", mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]);
#  endif
  return String(baseMacChr);
}

String getUniqueId(String name, String sufix) {
  String uniqueId = (String)getMacAddress() + name + sufix;
  return String(uniqueId);
}

Why this question? Because this piece of code is not unique and I know that there is a problem with the scope of the variables. (Well explained here: Returning a C string from a function - Stack Overflow ).

Ready to learn something new!

Yes, Seems to be safe. For those who want to know more here are some answers from stack overflow c++ - Is it safe returning Arduino String from a C function? - Stack Overflow

1 Like