使用你的宏:
#define SAFEMALLOC(SIZEOF) (malloc(SIZEOF) || (void*)(fprintf(stderr,"[%s:%d]Out of memory(%d bytes)\n",__FILE__,__LINE__,SIZEOF),exit(EXIT_FAILURE),0))
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
char *p = SAFEMALLOC(10);
char *q = SAFEMALLOC(2000);
printf("p = %p, q = %p\n", p, q);
// Leak!
return 0;
}
警告(应该是一个线索):
weird.c:8: warning: cast to pointer from integer of different size
weird.c:8: warning: initialization makes pointer from integer without a cast
weird.c:9: warning: cast to pointer from integer of different size
weird.c:9: warning: initialization makes pointer from integer without a cast
输出:
p = 0x1, q = 0x1
总之,不,这不是很安全!编写一个函数可能不太容易出错。