I get a segmentation fault when I declare a function pointer before main() and assign it with the address of a function inside main. What is the actual problem that occurs if the function pointer is declared before main()??
The code is given below:
#include <stdio.h>
#include <pthread.h>
void fun1(char *str)
{
printf("%s",str);
}
void (* funptr)(char *);
int main()
{
char msg1[10]="Hi";
char msg2[10]="Hello";
pthread_t pid1, pid2;
funptr=&fun1;
pthread_create(&pid1,NULL,(void *)(*funptr),(void *)msg1);
pthread_create(&pid1,NULL,(void *)(*funptr),(void *)msg2);
pthread_join(pid1,NULL);
pthread_join(pid2,NULL);
return 0;
}
Whereas when I declare funptr
inside main()
, it gives me the proper output. Would like to know what exactly is the issue.
The problem was with the thread id. I had used the same thread id "pid1" for both the threads and I was trying to join "pid2" also which resulted in segmentation fault. Following is the rectified code...
#include <stdio.h>
#include <pthread.h>
void fun1(char *str)
{
printf("%s",str);
}
void (* funptr)(char *);
int main()
{
char msg1[10]="Hi";
char msg2[10]="Hello";
pthread_t pid1, pid2;
funptr=&fun1;
pthread_create(&pid1,NULL,(void *)(*funptr),(void *)msg1);
pthread_create(&pid2,NULL,(void *)(*funptr),(void *)msg2);
pthread_join(pid1,NULL);
pthread_join(pid2,NULL);
return 0;
}
funptr
is already a function pointer. To cast it to void *
, all you need is (void *)funptr
. You are required to have the third argument of type void *(*) (void *)
, not cast your function to void*
. See pthread_create documentation
As Santhosh has written in the comments, the reason for the SIGSEGV
is that pthread_create()
is given as argument pointer to the same pthread_t
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With