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.

Syntax

String1.reserve(n_bytes);

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.

Example

String s1 = "Hello";

void setup() {
   // put your setup code here, to run once:
   Serial.begin(9600);
   Serial.println();

   s1.reserve(20);
   s1 = s1+" World!";
   Serial.println(s1);
   s1 = s1+" I'm now trying to exceed the reserved memory";
   Serial.println(s1);
}

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

Output

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.

Updated on: 29-May-2021

584 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements