String Object and memory

I believe the String object uses malloc to create varying lengths of characters? If so, is there a way to free() the object when it's not needed anymore?

Memory management on Strings would be good.

Not using the String class on a microcontroller would be even better. You gotta give up some of those crutches when you move from a full blown computer with gigabytes of RAM to a micro with 2K.

There's nothing that can be done with the String class that can't be done just as well with a char array. The only difference is that the char array won't potentially crash your program due to poor memory management.

If you change a string, I imagine the old memory is discarded and new memory allocated. Thus, the old memory is freed. However this may lead to heap fragmentation. If you are worried about memory I suggest you don't use String at all.

Yeah, I don't use String but I was going to make a tutorial for beginners and decided to use String so it's easier to understand so it got me thinking on how to it eats up memory and if it ever gets freed at all unless we manually free it somehow.

The memory management of all class objects in C++ including String is done via new and delete operators (which are often implicitly called by the compiler as things go out of scope etc). If you look inside the Arduino runtime you'll find in new.h and new.cpp that new and delete map directly to malloc and free.

In older versions of the String class there were bugs in some of the String operations that caused memory leaks (to do with the management of the char [] array used internally I believe). As I understand it the class is now free from space leaks like this, but I wouldn't necessarily trust it (!).

Whatever you do don't call free() on a C++ class object, that's just asking for a double free bug. Reserve malloc and free for dynamically allocated C structs and arrays if you have to use them.

On a machine with only 2k of RAM like the Uno the profligate use of dynamic memory allocation can result in unreliable code as there is no guarantee the sketch won't trample its stack at some random point, and explicit checking for low memory is a bit tedious (though possible). Statically pre-allocating storage is a more robust strategy, ie the opposite of best practice for code on a general purpose computer with GB of RAM!