【问题标题】:Function pointer allocated on the heap在堆上分配的函数指针
【发布时间】:2019-05-02 19:18:32
【问题描述】:

我想声明一个本地函数指针,在堆上为指针分配空间,动态指向不同的函数。

#include<stdlib.h>
#include<string.h>
#include<stdio.h>
#include<unistd.h>

void fun(){
 printf("fun");
}

typedef void(*fp)();

int main(){
 fp f; //local pointer
 f = malloc(sizeof(f)); //allocate space for a pointer on the heap
 (*f) = &fun; //write the address of fun into the space allocated in heap
 (*f)(); // so that the contents in f, is the address of fun
}

但我在(*f) = &amp;fun; 收到编译错误,内容为:error: lvalue required as left operand of assignment。我应该如何正确地做到这一点?

这看起来不像是 xy 问题:我想重现这里提到的漏洞:Use after free exploit

【问题讨论】:

  • 不需要分配任何东西。这里。 f=fun; 将做所有需要的事情。并致电 - f().
  • 函数指针指向代码空间,这在概念上通常与数据不同。在某些硬件(哈佛架构)上,它甚至在物理上有所不同
  • &amp;funfun 是等价的。你想要的只是fp f = fun; f() /*call fun*/; f = lol; f() /*call lol*/;

标签: c pointers malloc function-pointers


【解决方案1】:

您不能分配给*fp,因为该表达式具有函数类型。

fp 用于存储指针,在本例中是指向函数的指针。所以你不需要分配任何东西。只需分配函数的地址:

fp f;
f = &fun;
(*f)();

还要注意,函数类型的表达式会自动转换为指向该函数的指针,包括在调用它时,所以它的作用相同:

fp f;
f = fun;
f();

编辑:

如果你真正想要的是为函数指针动态分配空间,那么你需要一个指向函数指针的指针来存储它:

fp *f;                   // fp is void (*)(), so f is void(**)()
f = malloc(sizeof(*f));  // allocate space for function pointer
*f = func;
(*f)();     // func called

free(f);
fp *g;
g = malloc(sizeof(*g));   // possibly points to what f pointed to?
*g = evil_f;

(*g)();    // evil_func called

请注意,上面调用了未定义的行为,并且仅适用于不优化存储在 f 中的值并重用相同的内存区域分配给 g 的实现。

【讨论】:

  • 但这不是堆栈上的本地指针,指向函数吗?我希望它是 malloced 是有原因的。这甚至可能吗?
  • @rranjik 它是本地的,但指针包含一个在程序生命周期内有效的值(即函数的地址)。因此,您可以将该指针的内容传递给其他函数或从当前函数返回并安全使用它。
  • @rranjik, mallocobject 分配空间,并返回指向该空间的指针。没有办法为函数动态分配空间,也不需要它,因为C没有动态编写函数实现的机制。
  • @dbush 非常感谢!
猜你喜欢
  • 1970-01-01
  • 2020-12-19
  • 1970-01-01
  • 2013-04-14
  • 1970-01-01
  • 2021-09-01
  • 2020-09-02
  • 2018-08-24
  • 2011-03-05
相关资源
最近更新 更多