ionito:
I just would like to ask the community to give me simple examples to realize the total "String-wiping" from my existing code. For instance:
String logText = "SENSOR LOG";
...
logText = logText + " Recnum: " + rec;
Thanks
I tried that and it didn't crash:
void setup ()
{
Serial.begin (115200);
int rec = 42;
String logText = "SENSOR LOG";
logText = logText + " Recnum: " + rec;
Serial.println (logText);
logText = logText + " Recnum: " + rec;
Serial.println (logText);
}
void loop () {}
Output:
SENSOR LOG Recnum: 42
SENSOR LOG Recnum: 42 Recnum: 42
Now of course that would eventually crash if you loop adding to the string, what do you expect? But you need to provide a reproducible example that actually crashes then perhaps someone can fix it.
... this object (String) is so RAM-hungry that causes heap overflow without any warning to the developer.
I'm not sure what sort of warning you want. Looping consuming RAM isn't something the compiler can predict. And at runtime there is no screen to put a "blue screen of death" on. About all a microprocessor can do when you trash RAM is loop or reboot. Sounds like yours is rebooting.
Personally I don't use the String class because I am memory conscious. On the 328 chip I only have 2Kb of RAM to start with, and the program will be using some already for variables most likely. And heap fragmentation is a very real issue, and one hard to avoid.
Here's an example... allocate 200 x 10 byte blocks of memory (ie. use up your 2000 bytes). Then delete every second one. So notionally you have 1000 bytes free. Then try to allocate a single 20 byte block. You won't be able to because there is not a single 20 byte gap. So even with 1000 bytes of "free" memory you can do practically nothing with it. And string classes tend to do that, especially as you concatenate stuff (add to the end), which your example did. You have small strings, larger ones, even larger ones, etc.
You are asking to run out of memory if you do that.
Here is a test program that exercises the String class a bit:
String bar = "the question is not known";
int count1, count2;
void test ()
{
String foo = "the answer is 42";
if (foo == bar)
count1 ++;
if (bar == "the question is not known")
count2 ++;
}
void setup ()
{
Serial.begin (115200);
for (int i = 0; i < 10000; i++)
test ();
Serial.println ();
Serial.print ("count1 = ");
Serial.println (count1);
Serial.print ("count2 = ");
Serial.println (count2);
}
void loop () {}
That creates a local variable "foo" in the "test" function. Since it is a local variable it will be created every time through, thus causing memory allocations, and an assignment to the string. Then it does a couple of string comparisons.
The whole thing is done 10000 times, plenty of time to run out of memory. But it doesn't, it runs to completion and prints the result.
So, sorry, sounds like you have a program bug. If you can provide a reproducible bit of code that demonstrates that the String class is faulty, please do.