Detached pthread_create() leaks memory

2019-08-04 10:13发布

问题:

I'm developping an application in C in a Linux environment. I've noticed that the following code leaks tons of memory after only hundreds executions :

do {
    pthread_t               flushThread;
    pthread_attr_t          attr;
    logevent_thread_t       logThread = { Db , &do_curl };

    if (( pthread_attr_init ( &attr ) == 0 ) &&
        ( pthread_attr_setdetachstate ( &attr , PTHREAD_CREATE_DETACHED ) == 0 )  ) {
        pthread_create ( &flushThread , &attr , (void*)FlushThread , (void*)&logThread );
        pthread_attr_destroy ( &attr );
    }
} while(1);

When I started with the code, I only used pthread_create(), but when I noticed the leak, I started google'd and searched StackOverflow, and found the following URLs :

  • pthread_create memory leak
  • valgrind memory leak errors when using pthread_create

That's why I initialize the attributes and start the thread "detached". I also destroy the attributes. I can not use pthread_join() since I don't want a blocking call, I want my thread to live on his own.

Unfortunately, the leak is still there. I've no more ideas, and will get any further advice !

Thank you !


@arrowdodger: Calling pthread_detach() without setting any kind of attributes also leaks. I also tried with setdetach and pthread_detach() without success.

@drhirsch : I know it leaks because when I have it run for 1 day, I get a "Out Of Memory" kernel panic. Additionnaly, using top I can see more and more memoery dedicated to my process (but I understand the best way to minitor this is to use valgrind).

回答1:

What i read from your links is that you should call pthread_detach(), not create it with DETACHED attribute.