pthread memory leak in C programming

2019-08-15 22:03发布

问题:

I have the code below.

void *timer1_function(void * eit);
pthread_t timer1;
int thread_check1 = 0;

line72: thread_check1 = pthread_create( &timer1, NULL, timer1_function,  NULL);

Valgrind shows the output below and says that there is a problem in the line 72. what is wrong with the pthread_create usage above?

272 bytes in 1 blocks are possibly lost in loss record 2 of 5
  in main in main.c:72
  1: calloc in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so
  2: _dl_allocate_tls in /build/buildd/eglibc-2.15/elf/dl-tls.c:297
  3: pthread_create@@GLIBC_2.2.5 in /build/buildd/eglibc-2.15/nptl/allocatestack.c:571
  4: main in <a href="file:///home/user/Project-build-desktop-Qt_4_8_1_in_PATH__System__Release/../project/main.c:72" >main.c:72</a>

回答1:

When you create a thread, you allocate some memory with it. The task of cleaning up this memory is done through a call to pthread_join.

The reason this memory is not cleaned up upon thread exit is that these data contain information such as "thread's exit status", which the parent may want to check out later. Therefore, never joining the thread means never cleaning up that memory.

The concept of un-joined threads are similar to zombie processes.