Re: Cannot understand the following codes



On 2006-03-28, Alf P. Steinbach <alfps@xxxxxxxx> wrote:
* Ben C:
On 2006-03-28, Alf P. Steinbach <alfps@xxxxxxxx> wrote:
It's probably a void(*)(). But not matter what type it has, the cast is
undefined behavior in C++, and I believe also in C.

Why's it undefined behaviour? I can see that it invites undefined
behaviour, but not that it entails it-- if the value of
stGOFuncs.p_go_Measurements is a function of the correct type won't it
be OK?

It will be OK, /if/ the type is some pointer to function (but not if the
type is simply void*, in which case it's UB); I was too hasty there.

You're right, void * and function pointers are not compatible. I tried
this:

#include <stdio.h>

int f(int x)
{
return x * 2;
}

int main(void)
{
int (*q)(int) = f;
void *p = q; /* WARNING */
int (*r)(int) = p; /* WARNING */

int x = (*r)(3);

printf("Answer is %d\n", x);

return 0;
}

I had assumed void * was good for anything. But it's only good for data,
not functions.

I suppose on some machines functions might have a completely different
address space, be a completely different size etc., and the standard is
allowing for that...

Sorry about that... ;-)

Not at all, thank you, I was missing something.
.



Relevant Pages

  • Re: Function call evaluation order
    ... void f1 ... int i = 0; ... f1 has.completely undefined behavior since i is modified twice ...
    (microsoft.public.vc.language)
  • Re: Function call evaluation order
    ... void f1 ... int i = 0; ... has.completely undefined behavior since i is modified twice between ...
    (microsoft.public.vc.language)
  • Re: function prototype and arguments conversion
    ... void func ... that case 2 and 3 invoke undefined behavior? ... So, say, if you had 'int x;' and 'int;', and converted ... You want 6.5.2.2, paragraph 7, which covers the conversion rules for the ...
    (comp.lang.c)
  • Re: program is not crashing, after 10 iteration
    ... your code results in undefined behavior. ... Actually, it occurs much earlier, during the first iteration. ... ptr invokes UB. ... On many systems (where int has no trap representations and the ...
    (comp.std.c)
  • Re: I want my segmentation fault!
    ... no occurrences of free and a lot of routines returning pointers to ... int length_of_list; ... This invokes undefined behavior because ml1 has been freed. ... memory is really available for reuse, I'd be glad to know about it. ...
    (comp.lang.c.moderated)