Reputation: 1516
The below code gives seg fault for the second case but for the first part it is working fine . but both of them are doing the same thing . Here the pthread_join() call is not generating any error , but while printing the response from the pthread_join() it generates Segmentation fault . What the first one is doing is different from the second one ? and Where the second one is actually wrong ?
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
void * thread_ops(void *arg){
printf("Thread Start!\n");
int val=((int *)arg)[0];
printf("value at thread -> %d\n",val);
int * c=(int *)malloc(sizeof(int *));
*c=val;
pthread_exit((void*)c);
}
int main(){
pthread_t pt,pt2;
pthread_attr_t ptatr;
int ar[1]={1};
// working
pthread_attr_init(&ptatr);
int status;
status=pthread_create(&pt,&ptatr,&thread_ops,ar);
printf("Thread Stats : %d\n",status);
int *result;
pthread_join(pt,(void **)&result);
printf("Result is %d\n",*result);
// why does the next set of lines generate seg fault ??
void **result2;
status=pthread_create(&pt,&ptatr,&thread_ops,ar);
pthread_join(pt,result2);
int ** res2=(int **)result2;
printf("Result is %d\n",**res2);
return 0;
}
Thread Stats : 0
Thread Start!
value at thread -> 1
Result is 1
Thread Start!
value at thread -> 1
Segmentation fault (core dumped)
Upvotes: 0
Views: 110
Reputation: 70883
Instead of
void **result2;
pthread_join(pt,result2);
use
void *pvresult;
pthread_join(pt, &pvresult);
and as you expect an int
add the following:
int result = *((int*) pvresult);
and print it this way:
printf("Result is %d\n", result);
Also replace this
int * c=(int *)malloc(sizeof(int *));
by this
int *c = malloc(sizeof *c);
Upvotes: 1