Search code examples
linuxpthreadspthread-join

pthread_join(thread_id, &res) , if &res is not NULL - is free(res) needed?


I've stumbled across a code example here. The lines that caught my attention (all other lines skipped):

{  
...  
void *res;  
...  
s = pthread_join(tinfo[tnum].thread_id, &res);  
...  
free(res);      /* Free memory allocated by thread */  
}  

Can anyone deeper into pthreads than myself comment on the free(res), please? I have to say I have never seen this before, and that googling for 1-1.5 hours didn't give me any other similar examples.


Solution

  • In pthread_join(thread_id, &res) , if &res is not NULL - is free(res) needed?

    It depends whether the return value of thread was dynamically allocated (with malloc() & co).

    If you look at the function thread_start() on same page, you'll see that it has a return statement:

    return uargv;
    

    and uagrv was allocated with:

           uargv = strdup(tinfo->argv_string);
    

    Hence, the free() call is used in main() after the pthread_join() call. Because res is the filled with uargv (returned by the thread). You can conceptually assume there's a code like this inside pthread_join() function:

     if (res)
       *res = uargv;
    

    Here's it's allocated using strdup() (which internally allocates memory). So you free() it. If the thread simply has return NULL; (and free()'s the uargv itself) then you don't need free().

    The general answer is if you allocate something with malloc() family functions then you need to free().