I'm trying to parse with tinyxml2 a modest XML (3.4kb) to retrieve some data.
My ESP8266 crashes every time I try to use the toCharArray
method.
here's my code
// here I'm getting an http request
String payload = https.getString();
// checking the payload, it seems fine in console but I get some garbage characters when àèéùìò are printed
Serial.println(payload);
// Length (with one extra character for the null terminator)
int str_len = payload.length() + 1;
// Prepare the character array
char xml[str_len];
// Copy it over
payload.toCharArray(xml, str_len);
// there I'll parse xml with tinyxml2 but the MCU crashes before getting here
the length of the string is something around 3900, which I'm not sure can fit this kind of array on this device. If it's the case, what will be a better strategy ?
As you can imagine I'm just starting with the c language :)
EDIT: https.getString().c_str()
+ less variables was the right way to save memory
1 Answer 1
Function local variable are created on the stack, and in the case of an ESP8266, the total size is limited to 4096 Bytes - so, 3900 for one variable is cutting it close.
I would recommend you either use malloc/free
int str_len = payload.length() + 1;
// Prepare the character array
char *xml = (char *) malloc(str_len);
// Copy it over
payload.toCharArray(xml, str_len);
// there I'll parse xml with tinyxml2 but the MCU crashes before getting here
//
// when done, free the memory malloc'd
free(xml);
or, if you know an absolute maximum size for the string, e.g. 5000, make char xml[5001];
in the global scope
-
tried declaring a char with a size of 6000 in global and it reboots <<<stack<<< ets Jan 8 2013,rst cause:2, boot mode:(3,6) load 0x4010f000, len 1384, room 16 tail 8 chksum 0x2d csum 0x2d v951aeffa, the size of the string is ~5700Daniele– Daniele2019年04月26日 06:28:26 +00:00Commented Apr 26, 2019 at 6:28
-
got a compile error with malloc -> src/main.cpp:74:35: error: invalid conversion from 'void*' to 'char*' [-fpermissive]Daniele– Daniele2019年04月26日 06:29:58 +00:00Commented Apr 26, 2019 at 6:29
-
yeah, sorry was in a rush - hang on - there, fixedJaromanda X– Jaromanda X2019年04月26日 07:03:57 +00:00Commented Apr 26, 2019 at 7:03
-
tried declaring a char with a size of 6000 in global and it reboots
- really? that does seem oddJaromanda X– Jaromanda X2019年04月26日 07:05:15 +00:00Commented Apr 26, 2019 at 7:05 -
still no luck (event with malloc, which seems to work fine) but I think the problem could be elsewhere. For the sake of documentation I'll post the gist of the main file -> gist.github.com/leRenart/1b72db23371839fd5a7799ece63ad8edDaniele– Daniele2019年04月26日 19:09:47 +00:00Commented Apr 26, 2019 at 19:09
malloc
(andfree
) to useheap
memory instead