Bug 24345

Summary: pthread library libc_r causes memory leak at termination of joinable thread
Product: Base System Reporter: fishkin <fishkin>
Component: miscAssignee: Jason Evans <jasone>
Status: Closed FIXED    
Severity: Affects Only Me    
Priority: Normal    
Version: 3.5-STABLE   
Hardware: Any   
OS: Any   
Attachments:
Description Flags
file.diff none

Description fishkin 2001-01-15 13:10:01 UTC
Garbage collector looks into list of dead threads and freeing
resources only for threads with PTHREAD_DETACHED flag.
Unfortunattely pthread_join() doesn't set PTHREAD_DETACHED flag
on thread after fetching it return value. So, garbage collector
leave this thread in dead list and won't free() any resources
associated with it. This causes memory leak.

Fix: Should we simply set PTHREAD_DETACHED flag after sucessfuly
joining on thread ? But this is not solution for pthread_cancel(),
that also put threads in dead list w/o PTHREAD_DETACHED flag set.

How-To-Repeat: Simply start thread in joinable state, and then join on it.
------
#ifndef _THREAD_SAFE
#define _THREAD_SAFE
#endif
#ifndef _REENTRANT
#define _REENTRANT
#endif
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <pthread.h>

unsigned long brk_value = 0;

void *check_leak(void *arg)
{
    unsigned long current_brk = (unsigned long) sbrk(0);
    if (current_brk > brk_value)
        if (brk_value != 0)
            fprintf(stdout, "Data segment grows up by 0x%lX bytes\n", current_brk - brk_value);
    brk_value = current_brk;
    pthread_exit(NULL);
}

int main()
{
    pthread_t tid;
    pthread_attr_t attr;
    pthread_attr_init(&attr);
    pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
    for (;;) {
        if (pthread_create(&tid, &attr, check_leak, NULL)) {
            perror("pthread_create");
            exit(0);
        }
         else
            pthread_join(tid, NULL);
    }
}
-----
Comment 1 Jason Evans freebsd_committer freebsd_triage 2001-05-17 02:36:00 UTC
Responsible Changed
From-To: freebsd-bugs->jasone

I'm working on a solution to this problem.
Comment 2 Jason Evans freebsd_committer freebsd_triage 2001-06-23 01:47:30 UTC
State Changed
From-To: open->closed

Fixed in -current and RELENG_4.