diff --git a/Avoiding-pitfalls.md b/Avoiding-pitfalls.md index 4728990..0866280 100644 --- a/Avoiding-pitfalls.md +++ b/Avoiding-pitfalls.md @@ -99,20 +99,19 @@ but the actual result would be: because the same memory area has been reuse for each iteration. -The solution is to make sure that each string is available in memory by the time `printTo()` is called. -For instance, one could allocate all strings out of the loop: +The simplest solution is to explicitly duplicate the strings in the `JsonBuffer`: JsonArray& array = jsonBuffer.createArray(); - char buffer[16][3]; for (int i=0; i<3; i++) { - sprintf(buffer[i], "iteration %d", 0); - array.add(buffer[i]); + char buffer[16]; + sprintf(buffer, "iteration %d", 0); + array.add(jsonBuffer.strlen(buffer)); } array.printTo(Serial); The same principle applies to key and values of `JsonObject`. -Note: ArduinoJson 5.0 (currently in beta), make copies of `String` values but not `char*`. +Note: If you use `String` instead of a `const char*`, ArduinoJson calls `JsonBuffer::strdup()` implicitly. #### 7. Make sure the string isn't read-only