[asterisk-dev] Thread-local storage in linked lib cause memory leak

Tilghman Lesher tlesher at digium.com
Tue Jul 20 10:01:20 CDT 2010


On Tuesday 20 July 2010 02:45:41 Alex Massover wrote:
> Hi,
>
> Thank you for the reply. The problematic code in the library is:
>
> #define HOSTBUF_SIZE 1024
> static __thread	char tmphostbuf[HOSTBUF_SIZE];
>
> struct hostent *rc_gethostbyname(const char *hostname)
> {
>         struct  hostent *hp;
>         struct  hostent hostbuf;
>         int     res;
>         int     herr;
>         while ((res = gethostbyname_r(hostname, &hostbuf, tmphostbuf,
> HOSTBUF_SIZE, &hp, &herr)) == ERANGE) {
>                 return NULL;
>         }
>         if(res) return NULL;
>         if (hp == NULL) {
>                 return NULL;
>         }
>         return hp;
> }
>
> Looks like tmphostbuf is never freed, despite that thread exits (call ends
> and thread exits). If threads were not exiting the system would run of the
> threads (I run hundreds of thousands of calls).
>
> I fixed the problem by looking how ast_gethostbyname() is implemented and
> doing the same. It doesn't leak for me anymore.
>
> But I still don't understand why TLS implementation above leaks when linked
> to Asterisk. Maybe I'll create a simple lib, module and dialplan to
> demonstrate the behavior.

I'd venture a guess that as it's declared static, it's allocated when the
thread first references it, then it's kept as long as the process remains
active.  On the other hand, in Asterisk, our threadlocal routines allocate
memory from malloc, then free it when the thread ends.

-- 
Tilghman Lesher
Digium, Inc. | Senior Software Developer
twitter: Corydon76 | IRC: Corydon76-dig (Freenode)
Check us out at: www.digium.com & www.asterisk.org



More information about the asterisk-dev mailing list