Take the 2-minute tour ×
Arduino Stack Exchange is a question and answer site for developers of open-source hardware and software that is compatible with Arduino. It's 100% free, no registration required.

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.

share|improve this question

1 Answer 1

up vote 1 down vote accepted

new actually does work in arduino. it is defined in arduino/hardware/arduino/avr/cores/arduino/{new.h, new.cpp} using malloc. It is not part of avr-libc though (which your link concerns) and has not always been added by arduino.

Both of these work for me:

namespace{ //namespace to deal with .ino preprocessor bug
    class foo{
    public:
        int bar;
        foo(int a){
            bar = a;
        }
    };
}
...
//using new
foo *a = new foo[3]{{1},{2},{3}};

//How I would probably do this with malloc
foo *b = (foo*) malloc(sizeof(foo)*3);
b[0] = foo(2);
b[1] = foo(4);
b[2] = foo(8);

Placement new is not defined right now. I know that copying isn't quite the same, but it should work in most cases.

Of course, if you know exactly how long you want the array to be at compile time, you should probably make it a static/global variable so that you avoid using dynamic memory and the sketch ram usage number will be closer to correct.

share|improve this answer
    
Yep, new definitely works. I think my misunderstanding was based off of a really old arduino forum post forum.arduino.cc/index.php?topic=2249.0. My mistake –  BruceJohnJennerLawso Jul 8 at 14:43

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.