c - 为什么pthread会导致内存泄漏

标签 c memory-leaks pthreads posix valgrind

每当我创建 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;
}

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

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

最佳答案

线程是分配的资源,您在退出前没有释放它。您应该调用 pthread_join;这也将消除对您的骇人听闻和不正确的 sleep 循环的需要。

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

关于c - 为什么pthread会导致内存泄漏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17642433/

相关文章:

ptrace 是否可以导致被跟踪进程在不访问可执行系统调用指令的情况下执行系统调用?

c - 串口上不常见的波特率 - Linux

iphone - iPhone 内存泄漏问题

c - 使用 struct 与 pthread 进行合并排序

c - pthread_create() 后的段错误

c - Swift 使用 c 结构

c - 排序二维数组c程序

c++ - 内联函数的内存泄漏

c++ - 可能因异常而泄漏?

C++ PTHREADS - 无效的转换 void*(*)() 到 void*(*)(void*)