【发布时间】: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) = &fun; 收到编译错误,内容为:error: lvalue required as left operand of assignment。我应该如何正确地做到这一点?
这看起来不像是 xy 问题:我想重现这里提到的漏洞:Use after free exploit
【问题讨论】:
-
不需要分配任何东西。这里。
f=fun;将做所有需要的事情。并致电 -f(). -
函数指针指向代码空间,这在概念上通常与数据不同。在某些硬件(哈佛架构)上,它甚至在物理上有所不同
-
&fun和fun是等价的。你想要的只是fp f = fun; f() /*call fun*/; f = lol; f() /*call lol*/;
标签: c pointers malloc function-pointers