Arduino Forum

Products => Arduino Due => Topic started by: Nantonos on Oct 25, 2012, 04:20 pm

Title: Dynamic memory allocation in Audio library
Post by: Nantonos on Oct 25, 2012, 04:20 pm
I noticed this in arduino-1.5\hardware\arduino\sam\libraries\Audio\Audio.cpp

Code: [Select]
buffer = (uint32_t *) malloc(bufferSize * sizeof(uint32_t));


Sadly, memory allocation has bugs at present. Boilerplate:

Please note that, at present, the String library has bugs as discussed here (http://arduino.cc/forum/index.php/topic,95914) and here (http://arduino.cc/forum/index.php/topic,115552).

In particular, the dynamic memory allocation used by the String class may fail and cause random crashes.


Does this use of malloc imply that Audio will have he same issues that the use of the String clas has at present? Or does the C compiler and library used on the SAM architecture not have those issues? (And if not, does that mean String is also safe to use, on Due?)
Title: Re: Dynamic memory allocation in Audio library
Post by: cmaglie on Oct 25, 2012, 04:29 pm
I didn't make deep tests about malloc to verify the fragmentation problem, so i don't know if we'll have the same String issues.
What i can say for sure is that in many months of tests i didn't had any issue with it.

In any case, Audio library does only one allocation at the moment of instantiation of the Audio object, so it should be safe even with a buggy malloc.
C
Title: Re: Dynamic memory allocation in Audio library
Post by: pico on Oct 25, 2012, 05:15 pm
In any case, it isn't malloc() that is the problem in the AVR libs, it's free(). So if you malloc(), but never free(), there shouldn't be issues.
Title: Re: Dynamic memory allocation in Audio library
Post by: Nantonos on Oct 25, 2012, 06:08 pm
C, pico, thanks for the responses.

The Audio library does use free:

Code: [Select]
void AudioClass::end() {
dac->end();
free( buffer);
}


although it is not clear to me if that destructor is ever called, due to the setup+infinite-loop Arduino program structure.
Title: Re: Dynamic memory allocation in Audio library
Post by: cmaglie on Oct 25, 2012, 06:45 pm
Strictly speaking, this is not the destructor, but a method called "end", so you can call it explicitly using

Code: [Select]
audio.end();

in your sketch.