Active5 years, 9 months ago
I've been told (specifically in an answer to C++ Standard Library on Arduino, and in Stack Overflow question C++ string and Arduino String. How to combine them?)) that the Arduino compiler does not implement the
new
operator. However, I've written a program for the Arduino (in the Arduino IDE) which uses it, and it works perfectly.Here is a sample output to demonstrate its functionality:
So why do I keep hearing this? Are these people wrong, or do I simply misunderstand their meaning?
The way the Arduino delay function works is pretty straight forward. It accepts a single integer as an argument. This number represents the time in milliseconds the program has to wait until moving on to the next line of code. When you do delay(1000) your Arduino stops on that line for 1 second. Delay is a blocking function.
Community♦
Michael DorstMichael Dorst3,2981010 gold badges3131 silver badges5858 bronze badges
3 Answers
new
and delete
is defined as part of the Arduino distribution:/usr/share/arduino/hardware/arduino/cores/arduino/new.h
:The
angelatlargeangelatlargenew.h
is included in Printable.h
so you are getting it in your Arduino basic includes. These operators are not defined in AVR Libc though. My interpretation of these design choices: the Libc people thought it was a bad idea, whereas Arduino people are all about ease of use: if you want new
and delete
, please have them.3,64722 gold badges1212 silver badges3333 bronze badges
As you’ve demonstrated,
new
and delete
do work in principle on Arduino. The problem is that your Arduino has 2K of RAM for global variables, stack, and heap combined, so any substantial program you write for it has to be highly aware of memory usage.Therefore, for an embedded system like this, it is generally preferable to use static allocation (or possibly per-class dynamic allocation in some situations) rather than general purpose dynamic allocation: For simple programs, you don’t need dynamic allocation, and for complex programs, you can’t afford it.
microtherionmicrotherion2,79311 gold badge99 silver badges1515 bronze badges
Just because the platform doesn't predefine
operator new()
doesn't mean that you can't define it. In your code, presumably someone will have written a definition for the allocation function, so all is well.(I assume you're familiar with the difference between the
new
expression and the allocation function, which is confusingly called operator new()
.)Here's a baby example definition that should get a short program going:
This will obviously run out of memory very fast.
Kerrek SBKerrek SB
382k6767 gold badges731731 silver badges967967 bronze badges