4

As I heard, It is not safe to convert pointer to function to void*.

Okay, is it safe to cast

void (*enumerate) (void (*)(const struct foo *event, void *), void *)

to

void (*enumerate) (void (*)(const void *event, void *), void *)

and then call it with

void (*)(const void *, void *) as first argument, which treats its first void* as struct foo*?

4
  • @rkosegi Casting a function pointer to void* is undefined behavior. There's no guarantee it'll fit. It might work though, if you're lucky. Commented Jun 9, 2012 at 12:18
  • IIRC, it's not just UB; it's plain forbidden, so a strict compiler would not accept a program that tries (gcc -Wall -pedantic -Werror wouldn't). Commented Jun 9, 2012 at 12:21
  • See stackoverflow.com/questions/559581/… Commented Jun 9, 2012 at 12:22
  • I am not casting function ptr to void*. Commented Jun 10, 2012 at 9:00

1 Answer 1

7

No, this is not safe. It's not guaranteed by the C standard that a struct foo * and a void * have the same size and format. In general, casting function pointers to other function pointer types is a recipe for disaster. The safe solution is to insert an extra function that converts the arguments to the right type, just as you'd do when writing a comparison function for qsort that handles non-void * arguments:

static int compare_foo_as_voidp(void const *a, void const *b)
{
    return compare_foo((struct foo const *)a, (struct foo const *)b);
}

(As Oli Charlesworth writes in the comment, the cast itself is not the problem, but calling through the pointer causes UB.)

Sign up to request clarification or add additional context in comments.

7 Comments

+1. However, casting between function pointer types is ok (although silly), so long as you never call the function from the wrong pointer type.
Can you give an example of a version of C which has two different pointer sizes?
@AaronDigulla - x86 DOS made use of near and far pointers.
@AaronDigulla: On a Harvard architecture, code and data live in separate address spaces, so function pointers may well have a different size to object pointers.
@AaronDigulla: when a function is called through a pointer of the wrong type, the compiler will not convert its arguments.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.