Go Down

Topic: Memory leak in malloc/realloc/free. A workaround. (Read 3756 times) previous topic - next topic

fdivitto

There is a bug in the runtime C library version 1.6.4, which causes memory leaks using malloc/realloc/free standard library functions.
The bug is documented as bug 28135 in savannah-non-gnu web site and fixed in version 1.7.0. Unfortunately Arduino doesn't use this version, so I created a workaround function which fixes it:

struct __freelist
{
 size_t sz;
 struct __freelist *nx;
};

extern struct __freelist *__flp;
extern uint8_t* __brkval;

void fix28135_malloc_bug()
 {
   for (__freelist *fp = __flp, *lfp = 0; fp; fp = fp->nx)
   {
     if (((uint8_t*)fp + fp->sz + 2) == __brkval)
     {
       __brkval = (uint8_t*)fp;
       if (lfp)
         lfp->nx = 0;
       else
         __flp = 0;
       break;
     }
     lfp = fp;
   }
 }

It should be called whenever you call free() (or C++ delete), for example:

void* ptr = malloc(100);
....
free(ptr);
fix28135_malloc_bug();


I tested this workaround, but more in depth tests are necessary.
Any feedback or further fix is welcome.

Regards,
Fabrizio Di Vittorio

RuggedCircuits

Good work. But it might be easier to just download the malloc.c file from the 1.7.0 release and add it to any program that needs it (I'm guessing not many programs will use malloc() given how little RAM is available):

http://svn.savannah.nongnu.org/viewvc/*checkout*/trunk/avr-libc/libc/stdlib/malloc.c?root=avr-libc

This will require fewer (well...none) changes to user code and when the AVR-LIBC version catches up in the Arduino software the malloc.c files can just be dropped from user programs.

--
The Rugged Motor Driver: two H-bridges, more power than an L298, fully protected

fdivitto

Just in case someone (as me) don't like to mix sources coming from different library versions.

Go Up