Go Down

Topic: malloc() and free() how it works!? (Read 20728 times) previous topic - next topic


Hi guys, I am trying to understand how malloc and free works in arduino, there is no OS (as long as I know) running to manage the memory, anyone can help me to understand that? Links and books would be appreciated =D. :exclamation  ;D


This http://en.wikipedia.org/wiki/Malloc is a good starting point.
One thing, be sure you really understand this before using it in anger.
Try various test programmes etc.


Ah, sorry, I am used to dynamic memory allocation, but never used it in microcontrollers (In fact I only used the 8051, in college).

I understand the heap allocation when used with an OS, my question was: "How can we use it in Arduino since no entity is controlling the memory (as long as I know)?"

I found this thread: http://www.arduino.cc/cgi-bin/yabb2/YaBB.pl?num=1282050278/5 it appears to have some info about what I am seeking,




Not sure I follow all of that.
malloc and free are part of avr-libc. So, just use them!


How can we use [malloc/free] in Arduino since no entity is controlling the memory

There are not other entities trying to use the memory, either.  So when the program starts, it knows that it has full control all the memory in the chip.  Some may already be allocated to data or global variables, or the stack, but the rest can be assumed to be a chunk that malloc() can carve into smaller pieces are requested.


Sep 23, 2010, 08:09 pm Last Edit: Sep 23, 2010, 08:10 pm by simon.monk Reason: 1
But, I would really look at your design carefully first.

I just think dynamic memory allocation is fine in Big software - essential in the Objective C for an iPhone development I do in the day job. But rarely needed in embedded systems.

I used to work for a defence contractor, for embedded systems to do with displays, and there was simply a blanket ban on dynamic memory allocation.
I write books about Arduino and Electronics: http://simonmonk.org



Be very very careful when using this stuff, you can drain your memory really quick...


Well I used that in one modification in the WString, i made a function toCharArray, that follows the specification in the docs... It allocate and return a char[] to the user


Go Up