I have created a Button class, and I want to make several instances, and store pointers to them in an array. I am stuck with an error message that I cannot figure out myself:
o: In function setup': C:\DOCUME~1\ROB.R\LOCALS~1\Temp\build1815.tmp/Temporary_8220_7556.cpp:42: undefined reference to operator new(unsigned int)'
My code goes as follows:
#include "Button.h"
#define switchCount 2
Button *buttons[switchCount];
int pins[] = {2,3};
void setup()
{
int i;
for (i=0; i<switchCount; i++)
buttons = new Button(pins*);* } Can anyone comment or suggest a solution to this error message? R.
By default, the Arduino IDE and libraries does not use the operator new and operator delete. It does support malloc() and free(). So the solution is to implement new and delete operators for yourself, to use these functions.
Try adding that above your setup() and loop() in your main sketch.
Note that ANY use of dynamic memory allocations wastes a bit more memory besides the requested amounts. In the microcontroller world, it's usually better not to use new/delete/malloc/free at all, and to statically declare all of your storage instead.
To Rich_G:
Yes, button.h is Ok, in fact it does have a constructor and some methods. However that is irrelevant to my question.
To halley:
Thanks you for the solution. It did what was needed. I will consider making the instances static. It just seemed an easy way to keep track of state of more than 2 buttons -- have an instance for each, and monitor them from a loop, tailor the class to work without delay()-s. Your suggestion is good to keep in mind -- I am new to microcontrollers.
FWIW, I believe the gcc implimentation of free does the null pointer check. The stdlib documentation for free says:
_ The free(void *ptr) function causes the allocated memory referenced by ptr to be made available for future allocations. If ptr is NULL, no action occurs._
Since the mid-1980s, every free() I've ever seen has been documented to safely allow NULL as a no-op. The POSIX standard, which later became the "Single Unix Standard," mandates that free() exists and has a specific behavior. I can't register to download the SUS docs from the office to check if the standard mandates a safe free(NULL), but I bet $5 it does.
Ooh, that'll teach me to be pedantic! I must not have checked since the mid '80s. I had hoped to salvage a modicum of dignity by hiding in my Windows-centricity, but alas, even the Visual Studio documentation says that free(NULL) is ok. Thanks for setting me straight, guys.
No prob, mikalhart. Every time I'm wrong, I expect and appreciate a correction. Grumpy_Mike has definitely taught me a thing or two since I joined.
FYI: since WinNT3.5 or WinNT4.0, I think all the POSIX section 3 API was compliant. They were hoping for a POSIX stamp of approval around that timeframe. That's long before the ancient Visual C/C++ 6.0, so even Windows applies here.