C 下两个关于长度的问题

2018-12-15 14:20:13 +08:00
 smdbh

问题

  1. pfn_test 类型的 pfn, 长度使用++运算,为什么每次只加 1 ?
  2. func1,func2 加入到 section 中后,间隔变为 27 字节, 这个依据是什么,试了几个平台,这个值也不固定,如果要遍历 section 中的函数,这个 pfn++要如何写?

$cat main.c

#include <stdint.h>
#include <stdio.h>

typedef int (*pfn_test)(void);
#define UTEST      __attribute__(( unused, section("mysection")))

int UTEST func1(void)
{
    printf("func is %s\n", __func__);
}

static int UTEST func2(void)
{
    printf("func is %s\n", __func__);
}

extern pfn_test __start_mysection;
extern pfn_test __stop_mysection;

int main(int argc, char *argv[])
{
    printf("start sec %p\n", &__start_mysection);
    printf("stop sec %p\n", &__stop_mysection);

    printf("func1 %p\n", func1);
    printf("func2 %p, %lu\n", func2, func2 - func1);


    pfn_test pfn = &__start_mysection;

    printf("size %lu\n", sizeof(pfn));
    for (int i = 0; i <3; ++i) {
        printf("addr %p\n", pfn++);

    }

    pfn = &__start_mysection;
    for (int i = 0; i <2; ++i) {
        pfn();
        pfn += 27;

    }

    printf("done");
}

$ gcc main.c && ./a.out

start sec 0x4006a2
stop sec 0x4006d8
func1 0x4006a2
func2 0x4006bd, 27
size 8
addr 0x4006a2
addr 0x4006a3
addr 0x4006a4
func is func1
func is func2
2029 次点击
所在节点    程序员
3 条回复
Jex
2018-12-15 14:50:34 +08:00
C 语言并不支持函数指针运算,GCC -Wpointer-arith 有警告。
bilosikia
2018-12-15 15:15:54 +08:00
改成这样
printf("size %lu\n", sizeof(*pfn));

start sec 0x7fcf6ac007e2
stop sec 0x7fcf6ac00820
func1 0x7fcf6ac007e2
func2 0x7fcf6ac00801, 31
size 1
addr 0x7fcf6ac007e2
addr 0x7fcf6ac007e3
addr 0x7fcf6ac007e4
func is func1
Segmentation fault (core dumped)

对指针的加法运算是有指针指向的类型决定的,pfn ( pfn_test pfn = &__start_mysection; 这已经类型不匹配了)是指向的一个函数类型,sizeof(函数类型)= 1,
所以++ 只加了一

另外 c++是禁止对函数指针做加减法运算的
为什么 sizeof (函数类型)为一呢?
sizeof cannot be used with function types, incomplete types, or bit-field glvalues.
Jex
2018-12-15 15:48:57 +08:00
直接定义一个函数数组放到 section 里面,遍历这个数组就行了。你那两个函数指针之间的间隔就是其中一个函数代码体的大小。

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/517807

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX