Skip to main content
2 of 2
replaced http://stackoverflow.com/ with https://stackoverflow.com/

Malloc with Objects in Arduino libraries

My understanding of using dynamic memory on the arduino is that new/delete are not available, only malloc realloc and such C functions, as mentioned here:

C++ & the AVR

I am creating a library that defines an object type that needs to contain a dynamic list of other objects. In C++ I would define it something like this:

class Container
{
std::vector<otherObjectType> otherObjects;
};

which obviously does not work in the arduino without the C++ standard library.

My next choice would be to create a dynamic array using new, ie

otherObjects = new otherObjectType[3]
{ 
    {   (arguments to constructor...)
    },
    {   (arguments to constructor...)
    },
    {   (arguments to constructor...)
    }
};

But this does not work as well, since new is not supported...

finally I could try to use malloc as laid out here, but that also wont work without new.

I am wondering if I should just rewrite everything as structs, since that wont require me to worry about whether the constructor for the object was called when the memory was allocated in malloc.