Hi people. I wonder how I can free the pthreads' allocated memory?

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

#define NUM_OF_THREADS 10

void* print_thread_id(void* tid)
{
   printf("Greetings from thread %d\n", (*(int*)tid));
   pthread_exit(NULL);
}    

int main(int argc, char* argv[])
{
    pthread_t threads[NUM_OF_THREADS];
    int status, i;
    int* n_thread;

    for(i = 0; i < NUM_OF_THREADS; i++)
    {
      if((n_thread = malloc(sizeof(int))) == NULL)
        return EXIT_FAILURE;   

      *n_thread = i;
      printf("Main here. Creating thread %d\n", i);
       if((status = pthread_create(&threads[i], NULL, print_thread_id, n_thread)) != 0)
       {
          printf("ERROR. Thread error code: %d\n", status);
          exit(EXIT_FAILURE);
       }
       free(n_thread);       
    }
    return EXIT_SUCCESS;
}



==11701== LEAK SUMMARY:
==11701==    definitely lost: 0 bytes in 0 blocks
==11701==    indirectly lost: 0 bytes in 0 blocks
==11701==      possibly lost: 2,720 bytes in 10 blocks
==11701==    still reachable: 1,552 bytes in 4 blocks
==11701==         suppressed: 0 bytes in 0 blocks
==11701== Rerun with --leak-check=full to see details of leaked memory
==11701== 
==11701== For counts of detected and suppressed errors, rerun with: -v
==11701== ERROR SUMMARY: 4 errors from 1 contexts (suppressed: 2 from 2)

What you should do is

1 Not free the data at line 31, you can not know that the thread has not finished with it. Test by adding a short sleep in print_thread_id

Then either

2 Use pthread_join to detect when the thread has finished running then free the memory.

or (and my personal choice)

3 Assign ownership of that memory to the thread and free the memory in the thread function itself when the thread has finished with the data

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.