Added "Do not assume that strings are copied"

Benoit Blanchon
2015-06-26 22:36:01 +02:00
parent f9698b373c
commit fca9f4dc17

@@ -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`. 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. 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. 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. 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 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*`. 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*`.