typedefstruct test
{
int a;
int b;
}tester;
void setevent(void *in)
{
tester *recv = static_cast<tester*>(in);
cout << "recv->a: " << recv->a << endl;
//Seg Fault, how to handle this???
cout << "recv->b: " << recv->b << endl;
}
int main(int argc, char *argv[])
{
tester *one = new tester();
one->a = 10;
one->b = 20;
setevent((void *)1); // setevent((void*)(one))
}
In above code when setevent is called with the tester object, there is no issue, but if we pass random value it leads to seg fault. This is because static_cast is not type_safe, but can it be handled in any other way?
If static_cast fails you will get a compile error and the program executable will never even be built.
Your example has undefined behavior, not a failure or an error. Solution: don't use void *. Just don't. It's only required when working with a C library in some cases. It has no place in C++.