Ree*_*ril 5 c function-pointers segmentation-fault
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;
}
Run Code Online (Sandbox Code Playgroud)
Whereas when I declare funptr inside main(), it gives me the proper output. Would like to know what exactly is the issue.
问题出在线程ID上。我对两个线程都使用了相同的线程ID“ pid1”,并且尝试加入“ pid2”也导致了分段错误。以下是更正的代码...
#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;
}
Run Code Online (Sandbox Code Playgroud)
funptr已经是一个函数指针。要将其投射到void *,您所需要的就是(void *)funptr。您需要拥有类型为 的第三个参数void *(*) (void *),而不是将函数强制转换为void*。请参阅pthread_create 文档
正如 Santhosh 在评论中所写,其原因SIGSEGV是pthread_create()作为指向相同的参数指针给出的pthread_t。