Arduinojson: Free JsonObject ?

Created on 14 Dec 2017  路  5Comments  路  Source: bblanchon/ArduinoJson

Do I need to free JsonObject and JsonAaray ? Since aren't they created dynamically ?

https://github.com/bblanchon/ArduinoJson/blob/b55e57a7cf6c0910186ed09cc3717a272982a522/src/ArduinoJson/JsonBufferImpl.hpp#L15

question

Most helpful comment

Let's look at this statement again:

 JsonObject *ptr = new (this) JsonObject(this); 

This is not a regular call to the new operator, nor is it a placement new.
It is a call to an overloaded new operator in the base class JsonBufferAllocated:

void *operator new(size_t n, JsonBuffer *jsonBuffer) throw() {
    if (!jsonBuffer) return NULL;
    return jsonBuffer->alloc(n);
}

So ptr in the first statement is set to the result of jsonBuffer->alloc(n), which is an address inside the JsonBuffer.

All 5 comments

Hi @timpur,

No, you don't need to delete JsonArrays and JsonObjects.
They are allocated inside the JsonBuffer so the memory is released when you destroy the JsonBuffer.

Regards,
Benoit

I get that but won't the object it self use abit of memory ? Not just the content in the object ?

Edit

Looks like JsonObject doesn't declare any veriables so thus it won't use any memory in the heep, only reference memory in the buffer ? But I still feel like the object would use heep memory, other wise what is the pointer pointing to ?

Let's look at this statement again:

 JsonObject *ptr = new (this) JsonObject(this); 

This is not a regular call to the new operator, nor is it a placement new.
It is a call to an overloaded new operator in the base class JsonBufferAllocated:

void *operator new(size_t n, JsonBuffer *jsonBuffer) throw() {
    if (!jsonBuffer) return NULL;
    return jsonBuffer->alloc(n);
}

So ptr in the first statement is set to the result of jsonBuffer->alloc(n), which is an address inside the JsonBuffer.

Oh damn my C++ is nothing compared to yours !!!!! Forgive me for having doubt.

So it really is just a pointer to the buffer. That's good to know and thank you for explaining this and I hope others find this use full also.

You're welcome @timpur.

It is not the language that makes programs appear simple.
It is the programmer that make the language appear simple!

-- Robert C Martin

Thank you for your interest in ArduinoJson.
Don't forget to add a star if you like this library ;-)

Was this page helpful?
0 / 5 - 0 ratings