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

前端 未结 8 1689
孤街浪徒
孤街浪徒 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 19:52

    I should refresh my memory of the binary layout of the C calling convention at some point, but I'm pretty sure this is what is happening:

    • 1: It is not pure luck. The C calling convention is well-defined, and extra data on the stack is not a factor for the call site, although it may be overwritten by the callee since the callee doesn't know about it.
    • 2: A "hard" cast, using parenthesis, is telling the compiler that you know what you're doing. Since all of the needed data is in one compilation unit, the compiler could be smart enough to figure out that this is clearly illegal, but C's designer(s) didn't focus on catching corner case verifiable incorrectness. Put simply, the compiler trusts that you know what you're doing (perhaps unwisely in the case of many C/C++ programmers!)

提交回复
热议问题