Using new to create a pointer

Hello board,
This may seem like a simple questions for c++ but I am new to the arduino platform. I would like to create a pointer to a class using new. Here is my code example:

#include <NewSoftSerial.h>

void setup(){
 NewSoftSerial *mySerial = new NewSoftSerial(2,3);
}

void loop(){
}

It gives the following error, and I don’t know why.
sketch_jun28a.cpp.o: In function setup':** **C:\Users\ANDERS~1\AppData\Local\Temp\build3607339427993038982.tmp/sketch_jun28a.cpp:9: undefined reference to operator new(unsigned int)'

new() and delete() are undefined on Arduino.

Here's an article with more details: http://arduinoetcetera.blogspot.com/2010/04/implementing-new-and-delete-c.html

That article also has a replacement new() and delete() that you can use.

Thanks for clearing that up Andy. So if I want it on the heap, the best option is to make it a global variable or declare it outside of a function?

The Arduino memory map looks like this:

top of memory stack (grows down v) ... heap (grows up ^) uninitialized variables initialized variables bottom of memory (0x00000000)

So - if you want it on the heap, you have to malloc (or define new() yourself). If you're writing a library, sometimes this is the only choice, but often a bad choice for beginning programmers who aren't used to fragmentation and memory leaks.

If you're just writing a program, putting the new instance in either a global, or better yet, a static accessed with a function will put the variable in low memory. Then the heap grows on top of that, while the stack starts at high memory and works its way down.

Just remember that life gets bad when the heap meets the stack. :)

Andy thanks for this explanation. I hate to ask such simple questions being a computer engineer, but with any new system comes a learning curve. I will very much agree with your last statement, :astonished:

I think all you need is to replace this:

void setup(){
 NewSoftSerial *mySerial = new NewSoftSerial(2,3);
}

by

NewSoftSerial mySerial = NewSoftSerial(2,3);
void setup(){
}