Is cast function pointers safe to call?

In particular, will the following work as expected:

typedef void(*func_p)(void*); void foo(int* data) { printf("%i\n",*data); } int main(int argc, char** argv) { func_p bar; int x = 42; bar = foo; bar((void*)&x); return 0; } 

those. is it possible to rely on data pointers ( void* , int* , struct baz* , but not necessarily void(*)(void) ), always passed compatible?

+6
c casting function-pointers
source share
2 answers

The standard does not require this to work. The standard requires that char* and void* have the same representation and alignment requirements, all pointers to structures do this, and all connection pointers do that too. Although undefined behavior calls a casted function call anyway (ยง6.5.2.2p9), the same presentation and alignment requirements provide a practical guarantee that the call works (ยง6.2.5p27).

Other types of pointers should not behave this way, although I personally have not seen such a machine. It is theoretically possible that int* has a smaller sizeof than a char* for example (if int has more stringent alignment requirements than char , this might be wise). According to the correct calling procedure on such a machine, it would be almost impossible to call the pointer to the casted function.

+7
source share

If your code does not target strange ancient mainframes, it will work fine for all practical purposes. No modern machine uses different representations for different types of pointers, and I don't think it is realistic that any future machine will ever be. It is simply illogical and vice versa, very similar to one - it complements arithmetic.

If you are still worried or want to satisfy language purists, follow the caf.

+1
source share

All Articles