Problem in overriding malloc

后端 未结 9 1981
一整个雨季
一整个雨季 2020-12-30 09:24

I am trying to override malloc by doing this.

#define malloc(X) my_malloc((X))

void* my_malloc(size_t size)
{

    void *p = malloc(size);
    printf (\"All         


        
相关标签:
9条回答
  • 2020-12-30 09:47
    #define malloc(X) my_malloc((X)) 
    
    void* my_malloc(size_t size) 
    { 
        #define my_malloc(X) malloc((X)) 
    
        void *p = malloc(size); 
        printf ("Allocated = %s, %s, %s, %x\n",__FILE__, __LINE__, __FUNCTION__, p); 
        return p; 
    } 
    

    Here inside the function my_malloc, #define my_malloc(X) malloc((X)) will work. Outside this function it has no effect.Therefor, C malloc function will be invoked inside my_malloc

    0 讨论(0)
  • 2020-12-30 09:52

    You should use LD_PRELOAD to overwrite this kind of function (Library Interposer is the actual name that I could not remember)..

    Explanation here

    0 讨论(0)
  • 2020-12-30 09:52

    If you try to #define malloc (a reserved identifier) then the behaviour of your program is undefined so you should try to find another way to address your problem. If you really need to do this then this may work.

    #include <stdlib.h>
    
    #define malloc(x) my_malloc(x)
    
    void *my_malloc(size_t x)
    {
            return (malloc)(x);
    }
    

    Function like macros are only expanded if they are found as macro-name followed by (. The extra parentheses around malloc mean that it is not of this form so it is not replaced by the preprocessor. The resulting syntax is still a valid function call so the real malloc will still be called.

    0 讨论(0)
提交回复
热议问题