Go Down

Topic: what can be used instead of new[]? (Read 567 times) previous topic - next topic


why o why does the arduino's IDE not let me do this:
Code: [Select]

int* foo = new int[10];

and since it won't what are the alternatives I can use?
thank you


Have you tried this?

int * foo = new int(10);

You know by new you are invoking a constructor function, right?


You can't do it because its not C/C++.

int foo[10]; with give you an array of ten int's. Do not use new() on the Arduino until you understand C/C++ and even then think twice!.


Nick Gammon

Code: [Select]

// new[]
inline void * operator new[] (size_t size) { return malloc (size); }
// delete[]
void operator delete[] (void * ptr) { free (ptr); }

void setup ()
  int* foo = new int[10];

  // use foo here.
  delete [] foo; 
  }  // end of setup
void loop ()
  }  // end of loop

However be warned that free() has a bug in the current library that is supplied with the IDE.


Does free/delete have a bug or is there a more fundamental difficulty in implement free ?

Duane B
Read this
then watch this


Nick Gammon

There is a known bug in free:


Various threads discuss a minor change to fix it. However since the bug is not in the "source" part of the libraries, but the supplied pre-compiled part, it isn't quite as trivial for the end-user to fix it on their own.

Some of the other Arduino-like boards (I forget which exactly) are supplied with the fixed library.


thank you! i was tearing my hair out!


Will the bug have major consequences? should I check somehow for memory leak? Like using this test code http://andybrown.me.uk/wk/2011/01/01/debugging-avr-dynamic-memory-allocation/ and ending the program if i'm about to run out of memory?

Nick Gammon

The bug is more insidious than that. If you allocate memory, and then free it, it doesn't get freed correctly. Then you allocate a bit more and you might corrupt memory. It's not really to do with how much you allocate.

I think Andy Brown has a fixed library for the memory allocation. Try browsing his site for it.

I think you are fine if you just need to allocate and not free. For example, if you need to dynamically allocate "x" objects where you don't know what "x" is until runtime. But if you then free them, that's when the trouble starts (or might start).

Go Up