Problem in overriding malloc

后端 未结 9 2157
一整个雨季
一整个雨季 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:43

    To fix both the macro-replacement problem, and make LINE etc work as you're hoping they will:

    #define malloc(X) my_malloc((X), __FILE__, __LINE__, __FUNCTION__)
    
    void* my_malloc(size_t size, const char *f, int l, const char *u)
    {
    
        void *p = (malloc)(size);
        printf ("Allocated = %s, %d, %s, %x\n", f, l, u, p);
        return p;
    }
    

    (That way LINE and friends will be evaluated where the macro is expanded - otherwise they'd always be the same).

    Enclosing the name (malloc) in parantheses prevents the macro malloc from being expanded, since it is a function-like macro.

提交回复
热议问题