Pages: [1]   Go Down
Author Topic: Memory leak in malloc/realloc/free. A workaround.  (Read 3595 times)
0 Members and 1 Guest are viewing this topic.
0
Offline Offline
Newbie
*
Karma: 0
Posts: 2
Arduino rocks
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

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
Logged

0
Offline Offline
Faraday Member
**
Karma: 16
Posts: 2855
ruggedcircuits.com
View Profile
WWW
 Bigger Bigger  Smaller Smaller  Reset Reset

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
Logged

0
Offline Offline
Newbie
*
Karma: 0
Posts: 2
Arduino rocks
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

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

Pages: [1]   Go Up
Jump to: