C Function Pointer Type Compatibility

Having written a library that works with function callbacks, I often type (and call) pointers to types with the same call and the same signatures, but with one exception: they had parameters pointing to different types (all data) or void pointers.

I recently discovered that this might be unsafe, according to this: https://stackoverflow.com/a/464618/

In principle, as I understand it, if the types of arguments are compatible, this means that the types of function pointers are also compatible, and there should be no problems.

Now I have 3 questions.

First: does this mean that since pointers to different types are technically incompatible, what am I doing can cause undefined behavior?

Secondly: where (on which architectures) can I deal with it? Are there versions of Windows x86 or x64?

Third: where can I not avoid this?

+2
source share
1 answer
  • Yes it's UB itself
  • You will probably be able to avoid this in non-optimized non-debug builds. The optimizer can take advantage of pointer types to find out if there can be two aliases, logic that can fail if you lie about the actual types. Debug builds, of course, can simply be checked if there is a type mismatch.
  • Windows is not a compiler, so there is no reasonable question as it is. Generic Windows compilers optimize the build, and ICC is known to have improved optimizations.
+2
source

All Articles