Function of retval in pthread_join

1

I'm learning threading in C in OS. I don't know why following code is giving me segmentation fault. Can anyone help me here? I am also confused a bit about how pthread_join uses its argument void ** retval. What is its function?

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

void *thread (void *vargp) {
   int* arg = *((int*)vargp);
   return (void*)arg;
}   

int main () {
   pthread_t tid;
   int thread_arg = 0xDEADBEEF;
   int *ret_value;
   pthread_create(&tid, NULL, thread, &thread_arg);
   pthread_join(tid, (void **)(&ret_value));
   printf("%X\n", *ret_value);
   return 0; 
}
c
operating-system
pthreads
asked on Stack Overflow Feb 28, 2020 by Russ Brown

1 Answer

2

This is not correct:

int* arg = *((int*)vargp);  

(int*)vargp cast your void* to int*. But by writing int* arg = *((int*)vargp); you assing to the arg pointer the VALUE (0xDEADBEEF) of the argument vargp. This value (0xDEADBEEF) is not a valid adress.
what is the version of your compiler? because he must alert you :

invalid conversion from int to int*

You should write:

int* arg = (int*) vargp;
answered on Stack Overflow Feb 28, 2020 by Landstalker • edited Feb 28, 2020 by Landstalker

User contributions licensed under CC BY-SA 3.0