Hello, guys!
I was working with dynamic allocation of arrays of objects and some unexpected bugs appeared.
I discover that was related to initializing and destructing the objects in the array.
That is not done using malloc (realloc, and others) and free.
So i try using new[] operator (and delete) and i discover that (on the Arduino platform) they do not do this work too.
When i use some simple objects there is no problem. However, when the object internally allocate memory too (like the String object), that memory is not deallocated (because the destructor is not being called).
Here is an example to clarify:
#include "MemoryFree.h"
void setup(){
Serial.begin(9600);
//Prints initial free memory
printFreeMemory();
//do some allocating and deallocating
allocateDeallocate();
//The free memory should be the same
printFreeMemory();
}
void allocateDeallocate(){
for(int i=0; i < 5; ++i){
String * strings = new String[5];
delete strings;
}
}
void loop(){
}
void printFreeMemory(){
Serial.print("freeMemory: ");Serial.println(freeMemory());
}
I am using the MemoryFree library (Arduino Playground - HomePage) to display the use of RAM.
I look on the new.cpp file on the Arduino software and it is just making a call to malloc and free (without initializing or destructing nothing).
void * operator new(size_t size)
{
return malloc(size);
}
void * operator new[](size_t size)
{
return malloc(size);
}
void operator delete(void * ptr)
{
free(ptr);
}
void operator delete[](void * ptr)
{
free(ptr);
}
Finally i found on this post (c++ - Call constructor for object array allocated with malloc() - Stack Overflow) a way to solve that.
The deallocating worked ok:
//For each item call the destructor
for(int i =0; i < size; ++i){
(&items[i])->~String();
}
//Free the array's memory
free(items);
but the initialization generate a compilation error:
int size = 10;
String * items = (String *)malloc(size * sizeof(String));
for(int i =0; i < size; ++i){
String * s = &items[i];
new(s) String();
}
error:
error: no matching function for call to ‘operator new(unsigned int, String*&)’
<path to Arduino>/Arduino/hardware/arduino/cores/arduino/new.h:10: note: candidates are: void* operator new(size_t)
I hope that someone can help me to solve this problem. And i think that this should be corrected on the Arduino code too.
Thanks to all.