I am running into some serious memory leaks in my application, so I setup this extremely bare solution to test what happens when a String array goes out of scope...
I know that the old TextString implementation of String was lacking a destructor, but this current implementation seems to have it.
I am using this MemoryFree library (Note this linked code has now been fixed based on the accepted answer to this question).
The code examines two scenarios: Allocation of char array and string array in two different functions to force scope exit on both.
#include <MemoryFree.h>
void setup() {
// put your setup code here, to run once:
Serial.begin(9600);
int freeBefore, freeAfter;
//TEST ALLOCATION OF CHAR ARRAY//
freeBefore = freeMemory();
AllocateCharArr();
freeAfter = freeMemory();
Serial.println("CHAR*: Before " + String(freeBefore)
+ ", After " + String(freeAfter)
+ ", Diff " + String(freeBefore - freeAfter));
//TEST ALLOCATION OF STRING//
freeBefore = freeMemory();
AllocateStringArr();
freeAfter = freeMemory();
Serial.println("STRING: Before " + String(freeBefore)
+ ", After " + String(freeAfter)
+ ", Diff " + String(freeBefore - freeAfter));
}
void AllocateCharArr() {
char s[100];
}
void AllocateStringArr() {
String s[100];
}
void loop() { /* empty */ }
Output:
CHAR*: Before 1710, After 1710, Diff 0
STRING: Before 1645, After 1309, Diff 336
How come the String
array allocation is not wiped from memory?
String
array is much smaller (e.g., 10 elements)? – ouah Jan 15 '12 at 23:34