Typecasting function pointers to void *

B

bnoordhuis

Consider this:

int foo(int *a, int *b);
int (*bar)(void *, void *) = (void *)foo;

How legal - or illegal - is the typecast and are there real-world
situations where such code will cause trouble? I don't mean trouble
like in 'not compiling' but trouble like in 'crashing hard'.
 
P

pete

Consider this:

int foo(int *a, int *b);
(void *)foo;
How legal - or illegal - is the typecast and are there real-world
situations where such code will cause trouble? I don't mean trouble
like in 'not compiling' but trouble like in 'crashing hard'.

Converting a pointer to a function,
to a pointer to type void, is undefined.
 
D

Dave Vandervies

Consider this:

int foo(int *a, int *b);
int (*bar)(void *, void *) = (void *)foo;

How legal - or illegal - is the typecast and are there real-world
situations where such code will cause trouble? I don't mean trouble
like in 'not compiling' but trouble like in 'crashing hard'.

Conversions between function pointers and object pointers (void * is a
special case of "object pointers") is undefined.
I'd expect to see problems on systems with segmented memory spaces -
code and data segments are the first obvious way of using features like
segmentation, and the conversions between pointers into the different
segments may or may not be lossy (and there's no requirement that the
implementation fake lossless conversions if the underlying conversion
is lossy like there would be with void * and object pointers).

Any function pointer can be converted into any other function pointer
type and back to its original type without losing necessary information,
so if you need a "generic function pointer type" casting to something like
void (*)(void) and back will work. Note that this doesn't have the "able
to convert without a cast" feature that void * has for object pointers.


dave
 
E

Emmanuel Delahaye

Consider this:

int foo(int *a, int *b);
int (*bar)(void *, void *) = (void *)foo;

How legal - or illegal - is the typecast and are there real-world
situations where such code will cause trouble? I don't mean trouble
like in 'not compiling' but trouble like in 'crashing hard'.

The behaviour is undefined.

--
Emmanuel
The C-FAQ: http://www.eskimo.com/~scs/C-faq/faq.html
The C-library: http://www.dinkumware.com/refxc.html

"There are 10 types of people in the world today;
those that understand binary, and those that dont."
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,744
Messages
2,569,479
Members
44,900
Latest member
Nell636132

Latest Threads

Top