简体   繁体   English

如果函数指针与数组地址一起传递会发生什么

[英]What happens if function pointer is passed with array's address

typedef void(*FUNC)(void);
int main(void)
{
        //intptr_t m;
    const static unsigned char insn[4] = { 0xff, 0xff, 0xff, 0xff };
        FUNC function = (FUNC) insn;
        function();
}

The above code gives me an output as Illegal instruction. 上面的代码给了我作为非法指令的输出。 Can someone explain why ? 有人可以解释为什么吗? . Is it because the function pointer is not having the address of a function (as its having the address of an array it couldnot jump to the address) 是因为函数指针没有函数的地址(因为它具有数组的地址,所以无法跳转到该地址)

Since the pointer to the first element of the array is not a pointer to a function, you invoke undefined behaviour by calling a 'function' via the variable function . 由于指向数组第一个元素的指针不是指向函数的指针,因此您可以通过变量function调用“函数”来调用未定义的行为。 When you invoke undefined behaviour, anything can happen. 当您调用未定义的行为时,任何事情都会发生。 A crash with an illegal instruction is perfectly legitimate; 使用非法指令进行崩溃是完全合法的; so is wiping all the data off your disk. 所以是清除磁盘上的所有数据。

There is nothing that can be 'expected' according to the standards. 根据标准,没有什么可以“预期”的。 As hinted in the comments, what is likely to happen is that the bytes stored on the stack in the array insn (and in the rest of the stack, with the stack frame for main() and things like the argument list and the environment variables) will be treated as machine code. 正如评论中所暗示的那样,可能发生的情况是存储在数组insn中的字节(以及堆栈的其余部分,其中main()的堆栈框架,以及诸如参数列表和环境变量之类的东西main() )将被视为机器代码。 Fortunately for you, one of the bytes is an invalid (or illegal) instruction, and the program stops. 对您来说幸运的是,其中一个字节是无效(或非法)指令,程序停止了。

C11 J.5.7 Function pointer casts C11 J.5.7函数指针转换

1 A pointer to an object or to void may be cast to a pointer to a function, allowing data to be invoked as a function (6.5.4). 1指向对象或void的指针可以转换为指向函数的指针,从而允许将数据作为函数调用(6.5.4)。

2 A pointer to a function may be cast to a pointer to an object or to void , allowing a function to be inspected or modified (for example, by a debugger) (6.5.4). 2指向函数的指针可以强制转换为指向对象或void的指针,从而可以检查或修改函数(例如,通过调试器)(6.5.4)。

You are fine if you only cast the array name to a function pointer, but it's undefined behavior that you call it because it's not actually a function. 如果仅将数组名称转换为函数指针,就可以了,但是您将其称为未定义行为是因为它实际上不是函数。

You can try storing actual function pointer addresses in the array and then cast it back to function pointer and call them. 您可以尝试将实际的函数指针地址存储在数组中,然后将其强制转换回函数指针并调用它们。 However, unsigned char still won't work because it's too small, use uintptr_t instead. 但是, unsigned char仍然太小,因为它太小了,请改用uintptr_t

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM