String Manipulation

Dear All

Just trying to understand the memory allocation of String data type.
I have following code snippet:

String sample="hello";
sample+="World!";
sample+="Welcome to IoT";
Serial.println(sample.length());
Serial.println(sizeof(sample));

The output is as follows:

25
16

Does the String class dynamically allocate/extend the required memory to hold the message?
Is the above a safe method of string manipulation?

Or better way is to use the function reserve() to allocate the needed memory and manipulate the String object?

Thanks

Yes, it does.

That depends. If you do that a lot and have multiple String instances or other growing and shrinking dynamic objects in an application that runs for a long time, then I’d find other ways, since heap fragmentation might give you grief.

That’s one way, but I personally prefer using char[] over String.

1 Like

Thank you @ScruffR for the quick response. I understand.

I don’t know if your question was primarily about why sizeOf() gave you 16 when your string was 25 characters long. The function sizeOf() gives you the size of the type, not the size of the object you pass to it. So, 16 is the size of the String type, and has nothing to do with the length of the string you passed in; even a one letter string will give you 16. I believe that a string object contains a pointer to a buffer on the heap that contains the actual string data (this pointer and presumably something else are what occupies those 16 bytes). It’s that buffer that is dynamically allocated/extended to hold the string’s characters.

2 Likes

Hello @Ric

Thank you for the information.

Mainly, I wanted to confirm the memory management aspects of String class.Currently, I am working on an already developed code base in which a local String object is extensively manipulated. The resulting executable hangs after running properly for few days.(Hang could be of multiple reasons,but just trying to confirm the understanding whether this local String object manipulation could possibly be one of the reasons.)

As said above, after running for a few days and extensive use of String I’d not be surprised that your application fails (usually SOS panic error tho’).

@ScruffR, there are no SOS error reported till now, apart from fast blinking cyan/blue. There are few other observations which I would like to discuss in another thread.

All these inputs are helpful. I will update the issue analysis on this ticket if the issue is related to String object.

Good day.