简体   繁体   English

取消引用功能指针以交换功能

[英]Dereferencing a Function Pointer to Swap the Function

I tried to redefine malloc() in order to use a custom allocator without modifying the code. 我尝试重新定义malloc()以便使用自定义分配器而不修改代码。 Why doesn't the following code work? 为什么以下代码不起作用? Is using #define the only left solution? 使用#define是唯一剩下的解决方案吗?

void *(*malloc_ptr)(size_t) = malloc;
*malloc_ptr = my_malloc;

In order to reliably replace the memory allocation library, use LD_PRELOAD and pass it your own implementation of malloc and free. 为了可靠地替换内存分配库,请使用LD_PRELOAD并将其传递给您自己的malloc和free实现。

Clearly you can create your own variable called malloc_ptr and use that in all your functions, but be aware that other library functions will call the standard malloc . 显然,您可以创建自己的名为malloc_ptr的变量,并在所有函数中使用该变量,但是请注意,其他库函数将调用标准malloc

There is no assignment operator for function designators. 没有用于功能指示符的赋值运算符。

If you want to assign one function pointer to another function pointer then you should write 如果要将一个功能指针分配给另一功能指针,则应编写

malloc_ptr = my_malloc;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM