Reserve memory in Arduino for string manipulation

It may happen that a string may change length dynamically during the execution of a program.

If you want to ensure that there is always enough memory available for your string, you can reserve some memory using the reserve() function.



Where String1 is the string for which you are reserving memory, and n_bytes (unsigned int) is the number of bytes to be reserved in the memory.


String s1 = "Hello";

void setup() {
   // put your setup code here, to run once:

   s1 = s1+" World!";
   s1 = s1+" I'm now trying to exceed the reserved memory";

void loop() {
   // put your main code here, to run repeatedly:


The Serial Monitor output is shown below −

As you can see, even though we exceeded the reserved memory, there were no repercussions, because there was enough memory available. This function only helps set aside some memory for the string, so that we don’t face a shortage at runtime, especially in the execution of heavy codes.