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

标签 c language-lawyer

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

类似于:

#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 中的 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).

关于c - 从函数指针中读取数据是否合法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30157987/

相关文章:

c - rt linux中如何从用户程序访问内核内存?

c++ - ISO C++ 说这些是模棱两可的,即使第一个最差的转换比第二个最差的转换要好

c - 分配对象和结构的有效类型

c - 这种对非原型(prototype)函数声明的可疑使用是否有效?

c - 此泰勒级数代码不适用于 n=1 或 0 以外的任何值。为什么?

c - 我如何使用 Win32 API 启动带参数的进程?

c - 数组大小可变的结构

c - TCP 客户端数学运算无法正常工作

C "observable behavior"在 UB "undefined behavior"的上下文中

c - GCC:将结构归零