I tried to create POSIX thread with a void function like this:
void thread_func(void* p_Arg)
{
printf("Hello, World!\n");
}
int main(void)
{
pthread_t thread;
pthread_create(&thread, NULL, (void*)thread_func, (void*)NULL);
return 0;
}
The code works fine! But is it safe to cast thread_func to void* in this case?
No. Your code will crash on IA64. A function pointer cast is a bug waiting to happen. Just use the correct signature and return a dummy value like 0.
Also note that casting a function pointer (like
void (*)(void*)) to an object pointer (likevoid*) is also a potentially unsafe operation, since the C standard does not guarantee that object pointers and function pointers have the same representation. I don’t know of any architectures off-hand that use different representations, but it’s certainly possible for a function pointer to contain extra context bits not normally present in object pointers.So you should never cast a function pointer to an object pointer unless you’re using an implementation the expressly allows it — for example, POSIX systems require this, so the return value from
dlsym(3)can be safely cast from an object pointer to a function pointer.