为什么pthread导致内存泄漏

Joh*_*der 21 c valgrind posix memory-leaks pthreads

每当我创建一个pthread时,valgrind就会输出内存泄漏,

例如下面的代码:

#include <stdio.h>
#include <unistd.h>
#include <pthread.h> 

void *timer1_function (void *eit){
  (void) eit;
    printf("hello world\n");
    pthread_exit(NULL);
}

int main(void){
   pthread_t timer1;
   pthread_create( &timer1, NULL, timer1_function,  NULL);  ///////line13
   int i=0;
   for(i=0;i<2;i++){usleep(1);}
   return 0;
}
Run Code Online (Sandbox Code Playgroud)

valgrind输出

==1395== HEAP SUMMARY:
==1395==     in use at exit: 136 bytes in 1 blocks
==1395==   total heap usage: 6 allocs, 5 frees, 1,134 bytes allocated
==1395== 
==1395== 136 bytes in 1 blocks are possibly lost in loss record 1 of 1
==1395==    at 0x402A629: calloc (in /usr/lib/valgrind/vgpreload_memcheck-x86-linux.so)
==1395==    by 0x4011304: allocate_dtv (dl-tls.c:297)
==1395==    by 0x4011AAB: _dl_allocate_tls (dl-tls.c:461)
==1395==    by 0x4052470: pthread_create@@GLIBC_2.1 (allocatestack.c:571)
==1395==    by 0x8048566: main (test.c:13)
==1395== 
==1395== LEAK SUMMARY:
==1395==    definitely lost: 0 bytes in 0 blocks
==1395==    indirectly lost: 0 bytes in 0 blocks
==1395==      possibly lost: 136 bytes in 1 blocks
==1395==    still reachable: 0 bytes in 0 blocks
==1395==         suppressed: 0 bytes in 0 blocks
Run Code Online (Sandbox Code Playgroud)

虽然我使用手册页作为参考,为什么pthread_create会导致问题,我该如何解决?

R..*_*R.. 27

线程是已分配的资源,您在退出之前没有释放它.你应该打电话pthread_join; 这也可以消除你的hackish和不正确的睡眠循环的需要.

有可能即使你解决了这个问题,valgrind仍会看到"泄漏",因为POSIX线程的一些实现(我猜你正在使用glibc/NPTL)缓存并重用线程资源而不是完全释放它们.我不确定valgrind是否可以解决这个问题.


das*_*ght 5

我认为它会valgrind在程序退出时分析程序的状态,这可能在线程完成执行之前:两微秒可能不足以写入"Hello, world!\n"控制台.添加调用pthread_join应修复此泄漏:

pthread_join(timer1, NULL);
Run Code Online (Sandbox Code Playgroud)

  • 您只需为第二个参数传递空指针,而不是指向虚拟变量的指针. (4认同)