I'm getting a segmentation fault when trying to acess the 4th argument of pthread_join. Here is my code:
void* threadHandler(void* arg)
{
printf("arg: %c\n", *(char *) arg);
pthread_exit(0);
}
int main()
{
pthread_t threadA;
pthread_create(&threadA, NULL, threadHandler, "N");
void *retval;
pthread_join(threadA, &retval);
printf("retval: %d\n", *(int *) retval);
return 0;
}
Any idea as to why the last printf causes a segmentation fault error? How do i fix it? (it's my understanding that retval should contain the return value of the threadHandler, so in this case, it should be 0 right?)
Thanks in advance!
pthread_exittakes a pointer-to-void as the return value. You're returning(void *)0, which is a null pointer. Then you're dereferencing null pointer, which leads to undefined behaviour (crash in this case). - Antti Haapalaint, usually you're expected topthread_exitwith a pointer to the result of calculation in your thread, or NULL on error, or something like that. - Antti HaapalathreadHandler()but it is not returning anythin which will invoke undefined behavior. Most importantly, you should return a pointer instead and0is probably theNULLpointer. Then you dereference it invoking in theory UB and ultimately causing a crash. - Iharob Al Asimi