From fca9f4dc176f03d9afb1e2dab24b18a0e6968c41 Mon Sep 17 00:00:00 2001 From: Benoit Blanchon Date: Fri, 26 Jun 2015 22:36:01 +0200 Subject: [PATCH] Added "Do not assume that strings are copied" --- Avoiding pitfalls.md | 43 +++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 41 insertions(+), 2 deletions(-) diff --git a/Avoiding pitfalls.md b/Avoiding pitfalls.md index 02b248c..894b910 100644 --- a/Avoiding pitfalls.md +++ b/Avoiding pitfalls.md @@ -70,7 +70,47 @@ For instance, let's imagine that you parse `["hello","world"]`, like this: In that case, both `first` and `second` are pointers to the content of the original string `json`. So this will only work if `json` is still in memory. -#### 6. Make sure the string isn't read-only +#### 6. Do not assume that strings are copied + +By design ArduinoJson **never makes copies** of strings. +This allows it to work with full static memory allocation and ensure an efficient use of CPU cycles. + +But this can have subtle consequences... + +For instance the following code will not work as expected: + + JsonArray& array = jsonBuffer.createArray(); + for (int i=0; i<3; i++) { + char buffer[16]; + sprintf(buffer, "iteration %d", 0); + array.add(buffer); + } + array.printTo(Serial); + +One will probably expect the following result: + + ["iteration 0","iteration 1","iteration 2"] + +but the actual result would be: + + ["iteration 2","iteration 2","iteration 2"] + +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: + + 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]); + } + array.printTo(Serial); + +The same principle applies to key and values of `JsonObject`. + +#### 7. Make sure the string isn't read-only If you read carefully the previous section, you may have come to the conclusion that the JSON parser modifies the JSON string. @@ -96,4 +136,3 @@ If you replace it by: Depending on your platform, you may have an exception because the parser tries to write at a location that is read-only. In the first case `char json[]` declares an array of `char` initialized to the specified string. In the second case `char* json` declares a pointer to a read-only string, in fact it should be a `const char*` instead of a `char*`. -