Sub topic 3
The String Class Versus C Strings
This chapter assumes you can upload a sketch, use the Serial Monitor, and work with C-style arrays and pointers. It focuses on an AVR board such as the Uno, which has 2 KB of SRAM.
Why the String class is risky
The Arduino String class is convenient. It grows and shrinks as you add text. That growth allocates memory on the heap, and repeated allocations split free RAM into small pieces. This is called heap fragmentation. A sketch can have enough free RAM in total and still fail to get one block large enough.
C strings are plain char arrays with a fixed size. They never grow, so their memory use is known at compile time.
Fixed-size buffers and bounded formatting
Use a fixed buffer and snprintf(). The function stops writing once it reaches the buffer size, so it cannot overflow the array.
char buffer[32];
void setup() {
Serial.begin(9600);
int temperature = 23;
snprintf(buffer, sizeof(buffer), "Temp: %d C", temperature);
Serial.println(buffer);
}
void loop() {}Stack usage: local arrays, call depth and recursion
Local variables live on the stack, which shares SRAM with the heap. A large local array inside a function uses stack space only while that function runs. Deep call chains and recursion add more stack frames. Keep local arrays small, avoid recursion, and move large tables to global or static storage.
Saving small values in EEPROM
EEPROM is a small, non-volatile memory. It keeps values after power is removed. The Uno has 1 KB. Each cell survives about 100,000 writes, so use EEPROM.update() instead of EEPROM.put() when a value may not have changed.
Recognizing out-of-memory symptoms
Watch for these signs:
- Values that change for no reason
- The board resets or hangs
- Serial output that becomes garbled
- Sensor readings that drift after the sketch runs for a while
Memory sizes on other boards
| Board | SRAM | Flash | EEPROM |
|---|---|---|---|
| Uno | 2 KB | 32 KB | 1 KB |
| Mega 2560 | 8 KB | 256 KB | 4 KB |
| Due | 96 KB | 512 KB | None built in |
Check the datasheet for any other board before you plan memory use.
Exercise
Exercise
Why is snprintf() safer than sprintf() when you format text into a fixed buffer?
Show answer
snprintf() takes the buffer size as an argument and stops writing at that limit. sprintf() writes until the end of the text, so a long result can overflow the buffer and corrupt other variables.