Better then
#define ZFREE(p) do { free(p); p = NULL; } while(0)
#define ZFREE(p) do { free(p); p = NULL; } while(0)
#define free(p) do { free(p); p = NULL; } while(0)
And when you want to call the original free: (free)(p);
The preprocessor will not substitute this occurence of free. if(x) MACRO();
else something();
expands to if(x) { ... }; // Error!
else something(); #define FREE(ptrptr) do { \
__typeof__(ptrptr) const __x = (ptrptr); \
free(*__x); *__x = NULL; \
} while(0)
There might be a better way of doing it though. Also, __typeof__() obviously isn't standard C.Edit to add: I've honestly been moving away from using a macro and just putting both statements on one line like in the OP. For something so simple, using a macro seems like overkill.
Maybe someone else could figure out how to do it properly, since I'd definitely prefer a function.
int* p = malloc(sizeof(int));
FREE(&p);
What if we instead define the macro like this: #define FREE(ptr) do { \
__typeof__(ptr)* const __x = &(ptr); \
free(*__x); *__x = NULL; \
} while(0)
Then make usage slightly shorter, as well as more similar to free(): int* p = malloc(sizeof(int));
FREE(p);