0

I couldn't quite find a definitive answer to this one. My function pointer points to two functions that both take a pointer as an argument. Pointers in the same program are all the same size. Is the following still undefined behavior? The key part here is that the pointer argument in the function pointer signature points to an object with a different type.

#include <stdio.h>

struct Test
{
  int value;
};

int func1(void *userData)
{
  struct Test *test = userData;

  printf("func1: %i\n", test->value);

  return 0;
}

int func2(struct Test *userData)
{
  printf("func2: %i\n", userData->value);

  return 0;
}

int main()
{
  int (*func)(void *) = func1;
  struct Test test = {0};

  test.value = 9;

  func(&test);
  func = (int (*)(void *))func2;
  func(&test);

  return 0;
}

It compiles and runs fine on all compilers I have tried. Func1 is certainly correct (albeit not type safe because dealing with void*). However I am not sure about Func2 when being used / casted in this way.

I am basically looking at writing a callback system and want to avoid dealing with void* for safety and avoid code generation for maintenance.

Thanks!

Thomas Dickey
  • 51,086
  • 7
  • 70
  • 105
Karsten Pedersen
  • 419
  • 4
  • 11
  • You seem to be missing the fact that the *primary* type safety problem in a callback system such as you imagine is not with the types of the arguments to the callbacks, but with the types of the callbacks themselves. So yes, you want clients to provide callback functions with specific argument types, but to ensure that they do so, the variables and function parameters that receive function pointers should be typed appropriately. You can take other approaches, but every cast that is not provably correct reduces type safety. – John Bollinger May 15 '18 at 13:37
  • That is very true. However this line: func = (int (*)(void *))func2; Can be setup with macros to force type safety in various ways. For example, in a debug build it could try to call func2 with the test structure first (in an impossible if branch) that will flag up warnings of a pointer mismatch. But yes, I have read the existing question and mine is indeed a duplicate. Apologies for the noise. Not entirely happy with the solution but adhering to standard C is most important. Thanks guys. – Karsten Pedersen May 15 '18 at 16:23

0 Answers0