0

I try to compile and run the following:

valgrind --tool=memcheck --leak-check=full ./main

The program is compiled from the following source:

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

void* myfunc(void* arg) {
  printf("I'm in a new thread!\n");
  return NULL;
}

int main() {
  printf("I'm in the main thread!\n");

  pthread_attr_t attr;
  pthread_t thread;
  pthread_attr_init(&attr);
  pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
  pthread_create(&thread, &attr, &myfunc, NULL);
  pthread_attr_destroy(&attr);

  pthread_exit(0);
}

Sometimes, Valgrind reports that "no leaks are possible", but sometimes, Valgrind reports the following:

==59== Memcheck, a memory error detector
==59== Copyright (C) 2002-2017, and GNU GPL'd, by Julian Seward et al.
==59== Using Valgrind-3.13.0 and LibVEX; rerun with -h for copyright info
==59== Command: ./main
==59== 
I'm in the main thread!
I'm in a new thread!
==59== 
==59== HEAP SUMMARY:
==59==     in use at exit: 272 bytes in 1 blocks
==59==   total heap usage: 7 allocs, 6 frees, 2,990 bytes allocated
==59== 
==59== 272 bytes in 1 blocks are possibly lost in loss record 1 of 1
==59==    at 0x4C33B25: calloc (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==59==    by 0x4013646: allocate_dtv (dl-tls.c:286)
==59==    by 0x4013646: _dl_allocate_tls (dl-tls.c:530)
==59==    by 0x51E4227: allocate_stack (allocatestack.c:627)
==59==    by 0x51E4227: pthread_create@@GLIBC_2.2.5 (pthread_create.c:644)
==59==    by 0x40074A: main (in /home/runner/p3tdz9ggpuq/main)
==59== 
==59== LEAK SUMMARY:
==59==    definitely lost: 0 bytes in 0 blocks
==59==    indirectly lost: 0 bytes in 0 blocks
==59==      possibly lost: 272 bytes in 1 blocks
==59==    still reachable: 0 bytes in 0 blocks
==59==         suppressed: 0 bytes in 0 blocks
==59== 
==59== For counts of detected and suppressed errors, rerun with: -v
==59== ERROR SUMMARY: 1 errors from 1 contexts (suppressed: 0 from 0)

Is there any way to not have any reported "possibly lost" bytes with a detached thread?

karobar
  • 1,250
  • 8
  • 30
  • 61
  • 1
    Try `return (void *) 0;` instead of `pthread_exit` See my recent answer: [pthread still reachables](https://stackoverflow.com/a/72610521/5382650) And, definitely do _not_ do `pthread_exit`from `main` -g just do `return 0;` – Craig Estey Jul 09 '22 at 01:01
  • 3
    It’s hard to prove that no bytes are lost when there is a thread still active at process exit. The best solution is to join the thread as part of an orderly shutdown; then you can achieve deterministic behavior. – Jeremy Friesner Jul 09 '22 at 02:26

0 Answers0