Malloc issue

Joel Sherrill joel.sherrill@oarcorp.com
Sat Feb 18 22:00:00 GMT 2012


On 02/18/2012 11:55 AM, Hard Maker wrote:
> Hi list,
> I'm working with newlib in a cortex-m3 microcontroller (developing and
> study how work), debugging a little aplicatino I found the malloc
> assigments no depend of the type of data used. I'm not shure how explain
> this in english, but with this code is more simple:
>
> #include<stdio.h>
> #include "kit.h"
> #include "lcd_drv.h"
> #include<malloc.h>
>
> int main(int argc, char *argv[]){
>       char *m1;
>       short *m2;
>       int *m3;
>       float *m4;
>       long double *m5;
>       m1 = (char *)malloc(sizeof(char)); // 1 Byte
>       m2 = (short *)malloc(sizeof(short)); // 2 Byte
>       m3 = (int *)malloc(sizeof(int)); //  4 Bytes
>       m4 = (float *)malloc(sizeof(float));  // 4 Bytes
>       m5 = (long double *)malloc(sizeof(long double)); // 8 bytes
>       *m1=4;
>       *m2=4;
>       *m3=4;
>       *m4=4;
>       *m5=4;
>       while(1);
>       return 0;
> }
> All address assigned to m1, m2, m3, m4 and m5 pointers have 16 bytes of
> distance. The values show in debugger after last malloc are:
> m1 = 0x20005d90
> m2 = 0x20005da0
> m3 = 0x20005db0
> m4 = 0x20005dc0
> m5 = 0x20005dd0
> My question is: Why all pointers have 16 bytes of distance if they point
> to diferentes types of data? Searching about malloc aligment I found the
> default value is 8, there are some relationship?
>
The simple answer is that malloc() does not know the type and
has to return a pointer which is of proper alignment to be used
for any type.  In general this means that you tend to see
addresses from malloc be at least on 4 or 8 byte boundaries.
This is completely independent of the implementation.

I haven't looked at the newlib malloc implementation because
RTEMS uses its own implementation. But many malloc implementations
use buckets where anything < N comes from one bucket and say
N+1 to 2N comes from another bucket. This tends to prevent
fragmentation as it clusters malloc requests so freed memory
is of a size that is more likely to be reallocated. If this is the
style of algorithm newlib's malloc uses, then the smallest bucket
appears to be for allocations 1-16 bytes and are aligned on 16 byte
boundaries.

Since M3's often have very limited RAM, this might be wasteful
there and a simpler algorithm which could have more fragmentation
but "tighter" allocations.

The feedback we have gotten from RTEMS applications tends to
indicate that embedded real-time applications do most of their
allocations up front. Thus fragmentation tends to not be a problem.
But that is not a general statement for all embedded programs --
just what I tend to call "deeply embedded programs".

--joel sherrill
RTEMS
> I'm using newlib version 1.19.0
>
> thank's a lot.
>
> Sergio



More information about the Newlib mailing list