根据标准,从函数指针访问数据是否合法?
就像是:
#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,它似乎工作 – 但我想知道是否预期,或它是否是实现定义,并且该页面可能被操作系统读取保护?
最佳答案 从C标准的角度来看,不,它不是.
N1570中的附件J有一章关于共同扩展:
J.5 Common extensions
- 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函数指针强制转换中提到这个扩展:
- 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).