简体   繁体   中英

Dereferencing a Function Pointer to Swap the Function

I tried to redefine malloc() in order to use a custom allocator without modifying the code. Why doesn't the following code work? Is using #define the only left solution?

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.

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 .

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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