What happens if I cast a function pointer, changing the number of parameters

前端 未结 8 1675
孤街浪徒
孤街浪徒 2020-12-16 19:07

I\'m just beginning to wrap my head around function pointers in C. To understand how casting of function pointers works, I wrote the following program. It basically creates

相关标签:
8条回答
  • 2020-12-16 20:03
    1. Admitedly I don't know for sure, but you definitely don't want to take advantage of the behavior if it's luck or if it's compiler specific.

    2. It doesn't merit a warning because the cast is explicit. By casting, you're informing the compiler that you know better. In particular, you're casting a void*, and as such you're saying "take the address represented by this pointer, and make it the same as this other pointer" -- the cast simply informs the compiler that you're sure what's at the target address is, in fact, the same. Though here, we know that's incorrect.

    0 讨论(0)
  • 2020-12-16 20:05

    To answer your questions:

    1. Pure luck - you could easily trample the stack and overwrite the return pointer to the next executing code. Since you specified the function pointer with 3 parameters, and invoked the function pointer, the remaining two parameters were 'discarded' and hence, the behavior is undefined. Imagine if that 2nd or 3rd parameter contained a binary instruction, and popped off the call procedure stack....

    2. There is no warning as you were using a void * pointer and casting it. That is quite a legitimate code in the eyes of the compiler, even if you have explicitly specified -Wall switch. The compiler assumes you know what you are doing! That is the secret.

    Hope this helps, Best regards, Tom.

    0 讨论(0)
提交回复
热议问题