Hovering a function pointer to a type that takes more arguments

As far as I know, casting between incompatible function pointers, for example:

void aUnaryFunction(int a1)
{
    /* .... */
}

void doSomethingWithFn()
{
    typedef void(*BinaryFn)(int, const char*);
    BinaryFn aBinaryFunction = (BinaryFn) &aUnaryFunction;
    aBinaryFunction (3, "!!!");
}

should never be executed, like "undefined behavior" according to the C standard.

However, I don’t understand why, given how function calls work in C, this example is unsafe. All I do is ignore the argument.

Assuming that the handling of the first int argument is consistent, all that will happen is that const char * will be put into the register when it doSomethingWithFn()calls aBinaryFunction, aUnaryFunctionwill be executed as expected, and const char * can be overwritten in time aUnaryFunction, but this is fine because nothing else will use it in any way.

- , ? ( - ?)

+3
3

, C " " - , C.

, (, x86 stdcall) , , , , .

+6

. , "", , ? , , ?

, , , , Standard undefined - .

+5

By the way, "undefined behavior" is the secret code for "do not do this, it is NOT safe!".

This means that it will not work on different machines or even different versions of the same compiler on the same computer.

0
source

All Articles