在堆上分配的函数指针
Function pointer allocated on the heap
我想声明一个局部函数指针,在堆上为指针分配 space,动态地指向不同的函数。
#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
你不能给 *fp
赋值,因为那个表达式有函数类型。
fp
用于存储指针,在本例中是指向函数的指针。所以你不需要分配任何东西。只需分配函数的地址:
fp f;
f = &fun;
(*f)();
另请注意,函数类型的表达式会自动转换为指向所述函数的指针,包括在调用函数时,因此也是如此:
fp f;
f = fun;
f();
编辑:
如果你真正想要的是为函数指针动态分配space,那么你需要一个指向函数指针的指针来存储它:
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
的实现。
我想声明一个局部函数指针,在堆上为指针分配 space,动态地指向不同的函数。
#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
你不能给 *fp
赋值,因为那个表达式有函数类型。
fp
用于存储指针,在本例中是指向函数的指针。所以你不需要分配任何东西。只需分配函数的地址:
fp f;
f = &fun;
(*f)();
另请注意,函数类型的表达式会自动转换为指向所述函数的指针,包括在调用函数时,因此也是如此:
fp f;
f = fun;
f();
编辑:
如果你真正想要的是为函数指针动态分配space,那么你需要一个指向函数指针的指针来存储它:
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
的实现。