Low on memory

I've been told to stay away from stings because they burn more memory than char arrays so I've been using:

char text = "Hello World"

but if you want to append to it like:

strcat(text, "!");

is that still burning more memory just because I used that command?

Perhaps you were being warned against the String class of objects.

This line:

char text[] = "Hello World";

sets aside 12 bytes of SRAM and initializes them.

This line:

strcat(text, "!");

will set the 12th and 13th bytes of the 12-byte array to '!' and '\0' (Null terminator). This is BAD because it writes off the end of your array.

One easy way to conserve SRAM is to change:

Serial.print("String constant");


Serial.print(F("String constant"));

The F() macro tricks the compiler into leaving the string constant in FLASH (program) memory and gives the .print() method information that allows it to fetch the string constant directly from FLASH. Without it, all of those string constants have to be copied into valuable SRAM before your sketch even starts.

Thanks johnwasser, it brings to my attention to be very careful with how big the char array is first allocated. However, is the code above use the least amount of RAM or is there a better way to program/code it. - thanks

That code won't work properly, whenever you want to store a string, whether it is with the String class or using c style strings, you need to reserve a section of memory as long as your string. The way the String class gets around this is to reserve a chunk of memory (I think it is in blocks of 15 bytes?), that it stores your string in. When you get the to the end of the block it either reserves more memory at the end of it or it makes a new block somewhere and moves everything into there, freeing the old memory. This, along with the overhead of the class members etc. means that the String class is quite memory hungry, and especially when you have many short strings wastes a lot of memory.
c style strings are just arrays of chars that are terminated by a 0 or NULL character. This means it is up to the programmer to determine how much memory to allocate to them. To do this you need some idea before hand as to how long your strings will become, you can then allocate additional memory as needed e.g:

char myStr[80]="hello";

creates a char array which is 80 bytes long:


This then leaves you space to add characters to the string as you want, and you can use functions like strcat without any problems (as long as you don't exceed the length)
To have arrays that dynamically size you would have to use the malloc functions, but be aware that each time you do this you are going to be copying the whole array, which is slow and requires you to keep track of allocated memory, if you really need dynamically allocated strings then this is the time to use the String class, but these cases are actually quite rare and can almost always be avoided.