Adding to String object too slow?

Hi,

I'm working with GSM module and with some HTTP GET requests. Currently everything goes fine but I'm not able to save the data which I get from server. I can output it with Serial.print easily and nothing goes missing but if I try to add it to String the data gets corrupted.

If I use Serial.print(char(mySerial.read())); I get the following (as expected)

GET /report.php?xxxxxxxxxxxxx HTTP/1.0
Host: xxx.xxx.xxx

SEND OK
HTTP/1.1 406 Not Acceptable
Date: Tue, 04 Oct 2011 21:38:20 GMT
Server: Apache
Content-Length: 0
Connection: close
Content-Type: text/html

However if I change the code to return_data+= char(mySerial.read()); I get the following saved to return_data:

GET /report.php?xxxxxxxxxxxxxxxxxxxxxxx HTTP/1.0
Host: xxx.yyyxx


SEND OK
HTTP/1.1 406 Not Acceptable
Date: Tue, 04 Oct 2011 21:40:31 GMT
Server: Apache
Coneh
nt sCeT:tm

CLOSED

Any ideas where's the problem or is adding to String object just too slow operation? Any ideas how to get around this?

When you concatenate strings like that, memory is being continuously dynamically allocated, each time one byte longer. You are almost certainly running out of available RAM (because of memory fragmentation).

I suggest you decide in advance how much you are expecting, and just add to the end of a statically-allocated buffer.

Lorvija:

Serial.print(char(mySerial.read()));

Are you checking for mySerial.available() before calling mySerial.read()? If not you may be filling a lot of memory with 0xFF characters.

[quote author=Nick Gammon link=topic=74320.msg560039#msg560039 date=1317765795] When you concatenate strings like that, memory is being continuously dynamically allocated, each time one byte longer. You are almost certainly running out of available RAM (because of memory fragmentation).

I suggest you decide in advance how much you are expecting, and just add to the end of a statically-allocated buffer. [/quote]

Thanks for the hint! I've mostly worked with PHP so never had to think stuff like that. Works like a charm now.

johnwasser: Yeah I'm also checking myserial.available() before so that shouldn't be the problem.

I really don't like any kind of dynamic allocation in an embedded system.

For me the String class is not a good idea. Essential for Java, but not a good idea when you only have 1 or 2k of RAM.

Si: I really don't like any kind of dynamic allocation in an embedded system.

For me the String class is not a good idea. Essential for Java, but not a good idea when you only have 1 or 2k of RAM.

+1!!!!