#define SAFE_FREE(p) do { free(p); p = NULL;} while(0)
一般情况下我们会写成:
#define SAFE_FREE(p) { free(p); p = NULL;}
#include <stdio.h> #include <stdlib.h> #define SAFE_FREE(p) {free(p); p = NULL;} int main(int argc, char *argv[]) { int* ptr = (int*)malloc(sizeof(int) * 4); // error C2181: 没有匹配 if 的非法 else if (NULL != ptr) SAFE_FREE(ptr); else printf("Has already free!\n"); return 0; }
如下定义则正确:
#include <stdio.h> #include <stdlib.h> #define SAFE_FREE(p) do{free(p); p = NULL;} while(0) int main(int argc, char *argv[]) { int* ptr = (int*)malloc(sizeof(int) * 4); if (NULL != ptr) SAFE_FREE(ptr); else printf("Has already free!\n"); return 0; }
如果宏函数过大,定义成多行:
#define SAFE_FREE(p) \ do\ {\ free(p);\ p = NULL;\ }\ while(0)