Segmentation error after calling pthread_join ()

I wrote the following code using the POSIX pthread library:

#include<stdio.h> #include<stdlib.h> #include<pthread.h> pthread_t pid1,pid2; void *test(void *arg) { void **end; printf("\nNew Thread ID: 0x%x\n",(unsigned int)pid2); pthread_join(pid1,end); printf("\nNew Thread going to go off\n"); printf("\nNew Thread ID: 0x%x\n",(unsigned int)pid2); return ((void *)NULL); } int main() { pid1 = pthread_self(); pthread_create(&pid2,NULL,test,NULL); printf("\nMain Thread ID: 0x%x\n",(unsigned int)pid1); sleep(2); printf("\nI am going off\n"); pthread_exit(0); } 

When executing the code, I got the following output:

  Main Thread ID: 0xb7880b30
 New Thread ID: 0xb787eb70
 I am going off
 Segmentation fault

When I studied, the thread (pid2) that calls pthread_join will block until the thread passed in the argument (pid1) calls pthread_exit (). And pthread_exit () is used to stop the execution of a specific thread, allowing everyone else to continue execution.

I want to know why I finally got Segmentation Fault.

Please explain to me correctly.

+6
source share
4 answers

You are using the uninitialized variable void **end; , which leads to undefined behavior:

 pthread_join(pid1,end); 

Instead, you should:

 void *end; pthread_join(pid1, &end); 

i.e. passing a meaningful pointer to the variable in which you want to get the result, not an uninitialized pointer.

+9
source

I think the problem is that your end pointer passed to pthread_join() does not actually point anywhere. Try the following:

 void *test(void *arg) { void *end; // <=== printf("\nNew Thread ID: 0x%x\n",(unsigned int)pid2); pthread_join(pid1,&end); // <=== printf("\nNew Thread going to go off\n"); printf("\nNew Thread ID: 0x%x\n",(unsigned int)pid2); return ((void *)NULL); } 
+5
source

A segmentation error means that you tried to access memory or go to some place in memory that the OS did not allow you to execute code or read / write. In this case, when your child child should return after calling pthread_join() , since the OS cleared the main parent process and recovered all the memory used by the main parent process (including the execution code, as well as the stack space, empty space, etc. .)? ... This is definitely not the memory that the user land stream has access to, therefore, the OS throws a segmentation error.

+1
source

You call pthread_exit () on the main thread, which then immediately exits the system itself, ending main (), ending the process. The second thread unlocks and gets into a very strange position! At this point, you are deeply immersed in the land of undefined behavior. You must call pthread_join from the main thread.

-2
source

Source: https://habr.com/ru/post/887226/


All Articles