Arduino Strings Are BIG!

Interesting test: I was wondering if you could avoid the automatic string copy to RAM by putting strings inside a subroutine:

 
#include <avr/pgmspace.h>
int freeRam () {
  extern int __heap_start, *__brkval;
  int v;
  return (int) &v - (__brkval == 0 ? (int) &__heap_start : (int) __brkval);
}
void sub(void)
{
  char *text="ssssssssssssssssssssssssssssssss";
  Serial.print("inside function: ");
  Serial.println(freeRam());
//  text[0]='\0';
}
void setup() 
{
  Serial.begin(9600);
  Serial.println(freeRam());
  sub();
  Serial.println(freeRam());
}
void loop() 
{
}

Run it, and you’ll get a memory display of RAM before, during, and after the subroutine call, something like this:

1840
inside function: 1834
1840

But uncomment the line

//  text[0]='\0';

and run again – likely, you’ll get something more like this:

1806
inside function: 1800
1806

What happened? In the first one, the compiler optimized the text string right out of the system – until you did something with it (like setting text[0]) then it put it back in, and with a vengeance: that string is now in free memory RAM from the start of the program (notice the value before the subroutine was called – no change after).

What does this mean? If you use strings, be careful of them – anywhere they exist they add to RAM usage. Of course, if you move your strings to program memory, that’s another matter…

SOME ITEMS YOU MIGHT ENJOY
3 Set Prototyping Prototype Shield A ProtoShield For Arduino UNO R3 Leonardo Pro
$9.99 (0 Bids)
End Date: Thursday Apr-24-2014 17:18:19 PDT
Bid now | Add to watch list
A 3D LED Cube elec Kit (8x8x8=512) compatible w Arduino/MSP430 no LEDS
$69.98 (0 Bids)
End Date: Thursday Apr-24-2014 15:53:08 PDT
Buy It Now for only: $94.98
Buy It Now | Bid now | Add to watch list
New Pro Mini atmega328 Board 5V 16M Arduino Compatible
$2.22 (6 Bids)
End Date: Thursday Apr-24-2014 15:02:25 PDT
Bid now | Add to watch list


2 thoughts on “Arduino Strings Are BIG!

  1. Nice tip – thanks, man! This is an example of tweaky-technical information conveyed to web-visitors done *RIGHT*. Straight-forward, concise, complete. Good job.

  2. If you’re worried about ram space, you should use the “const” statement (http://www.arduino.cc/en/Reference/Const) who is used to load the variable in ROM instead of RAM. Using const means that you’re not going to change the value during running time, but when dealing with menus in LCD displays or other constants its very useful.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>