我想将我对malloc / realloc的调用包装成一个宏,如果该方法返回NULL将停止该程序
我可以安全地使用以下宏吗?
#define SAFEMALLOC(SIZEOF) (malloc(SIZEOF) || (void*)(fprintf(stderr,"[%s:%d]Out of memory(%d bytes)\n",__FILE__,__LINE__,SIZEOF),exit(EXIT_FAILURE),0))
char* p=(char*)SAFEMALLOC(10);
它编译,它适用于SAFEMALLOC(1UL)
和SAFEMALLOC(-1UL)
但这是一种安全的方法吗?
答案 0 :(得分:9)
static void* safe_malloc(size_t n, unsigned long line)
{
void* p = malloc(n);
if (!p)
{
fprintf(stderr, "[%s:%ul]Out of memory(%ul bytes)\n",
__FILE__, line, (unsigned long)n);
exit(EXIT_FAILURE);
}
return p;
}
#define SAFEMALLOC(n) safe_malloc(n, __LINE__)
答案 1 :(得分:4)
使用您的宏:
#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
总之,不,它不是很安全!编写函数可能不太容易出错。
答案 2 :(得分:4)
不,它坏了。
似乎假设布尔值或运算符||
返回其参数,如果它被认为是真的,那不是它的工作方式。
C的布尔运算符总是生成1
或0
作为整数,它们不生成任何输入值。