interactive-matter / aJson

aJson is an Arduino library to enable JSON processing with Arduino. It easily enables you to decode, create, manipulate and encode JSON directly from and to data structures.
http://interactive-matter.org/2010/08/ajson-handle-json-with-arduino/
566 stars 136 forks source link

there seems to be a memory leak in the “print” method. #12

Open interactive-matter opened 13 years ago

interactive-matter commented 13 years ago
  1. there seems to be a memory leak in the “print” method.
  2. there is a peculiar way to handle .999 as .899.

code (run on Arduino Uno and JEELINK):

include

aJsonObject* JSONObject; aJsonObject* JSONhostCommand; aJsonObject* JSONhostParameter1; aJsonObject* JSONhostParameter2; aJsonObject* JSONhostLength;

int p1=1000; float p2= 999.99;

void sendFreeRAM(String text) { Serial.print (“[JL: free RAM "); Serial.print (text); Serial.print (": "); Serial.print (freeRAM()); Serial.println (" ]“); }

int freeRAM () { extern int heap_start, *brkval; int v; return (int) &v – (brkval == 0 ? (int) &__heap_start : (int) brkval); }

void setup() { Serial.begin(9600); }

void loop() { aJsonObject *JSONObjectOut; JSONObjectOut=aJson.createObject(); aJson.addNumberToObject(JSONObjectOut, “M”, 5); aJson.addNumberToObject(JSONObjectOut, “P1″, p1); aJson.addNumberToObject(JSONObjectOut, “P2″, p2); aJson.addNumberToObject(JSONObjectOut, “L”, 10.199);

sendFreeRAM(“1: JSON”); Serial.println(aJson.print(JSONObjectOut));

sendFreeRAM(“2: JSON”); aJson.deleteItem(JSONObjectOut);

sendFreeRAM(“3: JSON”); }

All memory alloc function in c/c++ are voodoo to me, so I could not find anything in the code. Do you have an idea?

output here is:

[JL: free RAM 1: JSON: 1330 ] {“M”:5,”P1″:1000,”P2″:999.98999,”L”:10.19900} [JL: free RAM 2: JSON: 1282 ] [JL: free RAM 3: JSON: 1282 ] [JL: free RAM 1: JSON: 1282 ] {“M”:5,”P1″:1000,”P2″:999.98999,”L”:10.19900} [JL: free RAM 2: JSON: 1234 ] [JL: free RAM 3: JSON: 1234 ] [JL: free RAM 1: JSON: 1234 ] {“M”:5,”P1″:1000,”P2″:999.98999,”L”:10.19900} [JL: free RAM 2: JSON: 1186 ] [JL: free RAM 3: JSON: 1186 ] [JL: free RAM 1: JSON: 1186 ] {“M”:5,”P1″:1000,”P2″:999.98999,”L”:10.19900} [JL: free RAM 2: JSON: 1138 ] [JL: free RAM 3: JSON: 1138 ]

pasky commented 11 years ago

aJson.print() returns a dynamically allocated string, it is your responsibility to call free() on the pointer when you are done with it, so you cannot just directly pass the return value to Serial.print(). Note that with https://github.com/interactive-matter/aJson/pull/29, it will be less hassle to print stuff to streams like this. :-)

litui commented 11 years ago

Just as an FYI for others who might encounter something that looks similar, the code is malloc'd in the print routine so make sure the pointer you're using is either newly created or freed in advance or weird stuff will happen. =)