Reputation: 35
I want to replace all the instances of a wrapper function around free() called myfree() with myfree2(). Unfortunately, I cannot get it to work because the second macro redefines the first. Why is the second macro redefining the first if it has no argument?
// I must delete this function or the macro will replace it as well and cause a syntax error!
void myfree(void *p)
{
if(p != NULL)
free(p);
}
void myfree2(void *p)
{
if(p != NULL)
free(p);
}
#define myfree(p) do { myfree2(p); p = (void *)0xdeadbeef; } while (0);
#define myfree myfree2
myfree(p); // Wrapper around free().
afunc(arg, myfree); // Wrapper is used as a function argument!
Upvotes: 0
Views: 1116
Reputation: 126203
The C preprocessor does not allow overloading of macros based on the number of arguments -- you can only have a single macro of a given name. You can get around this problem in your case by using redundant parentheses in the declaration of myfree
:
#define myfree(p) do { myfree(p); p = (void *)0xdeadbeef; } while (0)
void (myfree)(void *p)
{
if(p != NULL)
free(p);
}
myfree(p); // Wrapper around free().
afunc(arg, myfree); // Wrapper is used as a function argument!
Upvotes: 1