1

I wrote a program in C. In a for loop it creates 12 threads.

   for (i = 0; i < 12; i++)
   {
        status=pthread_create(&ntid[i],NULL,th_f,NULL);
        if (status != 0)
        {
                printf("Error in Creating Thread\n");
                exit(1);
        }
   }

Then I joined them as shown:

   for (i = 0; i < 12; i++)
   {
                ret=pthread_join(ntid[i],&retval);
        if (ret)
        {
                printf("Error joining\n");
                exit(1);
        }
        printf("Thread terminated with status %d\n", *((int*)retval));
        free (retval);
   }

The function that thread is executing is th_f . It has 1 malloc and it is freed after joining (as you can see in `free (retval);

The valgrind report on this program is given below:

==27123== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 4 from 1)
==27123== malloc/free: in use at exit: 1,552 bytes in 5 blocks.
==27123== malloc/free: 29 allocs, 24 frees, 4,864 bytes allocated.
==27123== For counts of detected errors, rerun with: -v
==27123== searching for pointers to 5 not-freed blocks.
==27123== checked 89,896 bytes.

and

==27123== LEAK SUMMARY:
==27123==    definitely lost: 0 bytes in 0 blocks.
==27123==      possibly lost: 0 bytes in 0 blocks.
==27123==    still reachable: 1,552 bytes in 5 blocks.
==27123==         suppressed: 0 bytes in 0 blocks.

So I need answers to these questions:

  1. There should be only 12 allocs and 12 frees.Why is the number double?
  2. Irrespective of how many threads are created, 5 allocs are always extra. They are not freed. Why?
0aslam0
  • 1,797
  • 5
  • 25
  • 42

1 Answers1

0

The extra allocations and frees are probably thread stacks. The five extra are probably used internally by the threading library -- as it says, they are not leaked but are still reachable.

David Schwartz
  • 179,497
  • 17
  • 214
  • 278