Char array that causes crashes

Hello

I have a struct that causes the ESP32S3 to crash, and I don't know why.

    struct NodeRegistry { 
      uint32_t address;
      char key[32];
      char devUniqueID[32];
      char friendlyName[32];
      char device_ids[32];
      char manufacturer[16];
      char model[16];
      char hardwareVersion[6];
      char firmwareVersion[6];
    };
    NodeRegistry mqttNodes[64];

When I try to fill the struct with data, the code crashes.
The source of the data causing the issue are Strings. I know it's bad, but the ArduinoJson library works with Strings.

String node_ids = payloadObj["node_ids"];

When I do this:

snprintf(node_reg.key, sizeof(node_reg.key), "%s", node_ids);

or this:

strcpy(node_reg.key, node_ids.c_str());

It crashes with a kernel panic error.

If I use Strings in the struct instead of char arrays, it works flawlessly. But the problem is that I need to store this struct into an EEPROM later, so it has to be fixed sized char arrays (I assume).

Can someone explain-me where the error is please?

I'm stuck on this for 2 days already :frowning:

please post a whole sketch that replicates the problem.

hypothesis: you missed the \0 at the end of the char array?

1 Like

Could you print the length of the node_ids String?

Serial.print(node_ids.length());

You can get at the underlying c string from a String with the node_ids.c_str()

The functions in <string.h.>, like strcpy and also like snprintf, work with zero-terminated character arrays, not with String objects.

It is best to avoid String objects on Arduino, as they cause memory problems and program crashes.

Right on the front page

char json[] = "{\"sensor\":\"gps\",\"time\":1351824120,\"data\":[48.756080,2.302038]}";

JsonDocument doc;
deserializeJson(doc, json);

const char* sensor = doc["sensor"];

If the type cannot be inferred from the rest of the statement, use as<T>

  JsonDocument j;
  j["foo"] = "abcdefghi";
  Serial.println(j["foo"].as<const char *>());

The "safest" C-string copy is with strlcpy; the worst it will do is truncate, and it does that safely unlike strncpy

  char buf[6];
  strlcpy(buf, j["foo"], sizeof(buf));
  Serial.println(strlen(buf));
  Serial.println(buf);

Consider storing the entire JSON payload. It will probably take more space because it stores the punctuation and field names. But you have more flexibility because none of the field sizes are fixed. Space you save on shorter values is available to others. And your code might be simpler: read it back into a JsonDocument and use it. No need for a separate struct and copying into it.

Thank you for your advises.

I found the error meanwhile.

It was related to another library (painlessmesh).

I'm sorry for the inconvenience.

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