Problem in overriding malloc

后端 未结 9 2114
一整个雨季
一整个雨季 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条回答
  •  梦毁少年i
    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 
    
    #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.

提交回复
热议问题