从函数指针中读取数据是否合法?

Is it legal to read data out of a function pointer?

根据标准,从函数指针访问数据是否合法?

类似于:

#include <stdio.h>

int test(){
    //
}

int main() {
    int (*fp)(void) = &test;

    int i=0;
    for(i; i<10; ++i)
        printf("%x", *(fp+i));
}

Running on ideone,它似乎有效——但我想知道它是否是预期的,或者它是否是实现定义的,并且该页面可能被 OS 读取保护?

函数指针在设计上是合法的。

自己操作指针在设计上也是合法的,但可能会导致未定义的行为,包括使程序崩溃。

我尝试将循环扩展到 10000 并出现运行时错误,可能是因为那里禁止内存访问。

从 C 标准的角度来看,不,不是。

N1570 中的 Annex J 有一章是关于常用扩展的:

J.5 Common extensions

  1. The following extensions are widely used in many systems, but are not portable to all implementations. The inclusion of any extension that may cause a strictly conforming program to become invalid renders an implementation nonconforming. ...

随后在 J.5.7 函数指针转换中提到此扩展:

  1. 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).