bblanchon / ArduinoJson

📟 JSON library for Arduino and embedded C++. Simple and efficient.
https://arduinojson.org
MIT License
6.74k stars 1.12k forks source link

Foreign keys marked as "owned" when processed by DeserializeJson() --> wrong memorySize could be reported #1318

Closed ewaldc closed 4 years ago

ewaldc commented 4 years ago

I don't know exactly at what version this started to go wrong, but I discovered it while testing my v5.x relocatable/compact port to 6.x. Somehow this was not captured by the very elaborate test suite (or at least I have not managed to get that far).

I found it while debugging a stack corruption after a failed deserialize yielding in "out-of-memory". The JsonDocument should have been properly sized but turned out to be too small.

PS. The test suite in "extra" is amazing, it helped me fix at least 30 defects in my port!

bblanchon commented 4 years ago

Hi @ewaldc,

It's been like that as far as I can remember. I knew this was incorrect, but it didn't have any impact at the time I wrote it. But you're right; it now causes an issue when we construct a JsonDocument from a JsonVariant.

This made me realize that we have a bigger issue. Now that strings are deduplicated, the result of JsonVariant::memorySize() can be significantly larger than JsonDocument::memorySize(). I really don't know how I can fix that without heap memory...

Best regards, Benoit

ewaldc commented 4 years ago

For the first issue there is a (simple) solution. For the second "issue", I am not really convinced this is an issue, at least in my simple mind:

Hence, I think JsonVariant::memorySize() does the right thing to provide a "copy safe" size which might be a little larger than optimal. In that case, calling shrinkToFit() afterwards will do a perfect job to minimize memory usage.