Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

pthread_create memory leak?

Whenever I run valgrind on my program, it is telling that I have possibly lost memory wherever I call pthread_create. I have been trying to follow the guidance on

valgrind memory leak errors when using pthread_create http://gelorakan.wordpress.com/2007/11/26/pthead_create-valgrind-memory-leak-solved/

and other various websites google gave me, but nothing has worked. So far I have tried joining the threads, setting an pthread_attr_t to DETACHED, calling pthread_detach on each thread, and calling pthread_exit().

trying PTHREAD_CREATE_DETACHED -

pthread_attr_t attr;
pthread_attr_init(&attr);
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);

pthread_create(&c_udp_comm, &attr, udp_comm_thread, (void*)this);
pthread_create(&drive, &attr, driving_thread, (void*)this);
pthread_create(&update, &attr, update_server_thread(void*)this);

I think I may have coded this next one with joining wrong...I am going by https://computing.llnl.gov/tutorials/pthreads/ and they have all their threads in an array so they just for loop. But I don't have them all in an array so I tried to just change it to work. Please tell me if I did it wrong.

void* status;
pthread_attr_t attr;
pthread_attr_init(&attr);
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);

pthread_create(&c_udp_comm, &attr, udp_comm_thread, (void*)this);
pthread_create(&drive, &attr, driving_thread, (void*)this);
pthread_create(&update, &attr, update_server_thread(void*)this);

pthread_join(c_udp_comm, &status);
pthread_join(drive, &status);
pthread_join(update, &status);

trying pthread_detach -

pthread_create(&c_udp_comm, NULL, udp_comm_thread, (void*)this);
pthread_create(&drive, NULL, driving_thread, (void*)this);
pthread_create(&update, NULL, update_server_thread(void*)this);

pthread_detach(c_udp_comm);
pthread_detach(drive);
pthread_detach(update);

trying pthread_exit -

pthread_create(&c_udp_comm, NULL, udp_comm_thread, (void*)this);
pthread_create(&drive, NULL, driving_thread, (void*)this);
pthread_create(&update, NULL, update_server_thread(void*)this);

pthread_exit(NULL);

If anyone can help me figure out why none of this is working I would be very grateful.

like image 968
Sterling Avatar asked Jul 02 '26 03:07

Sterling


1 Answers

glibc doesn't free thread stacks when threads exit; it caches them for reuse, and only prunes the cache when it gets huge. Thus it always "leaks" some memory.

like image 131
R.. GitHub STOP HELPING ICE Avatar answered Jul 03 '26 17:07

R.. GitHub STOP HELPING ICE