我想将我对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);
Run Code Online (Sandbox Code Playgroud)
它编译,它在这里工作SAFEMALLOC(1UL),SAFEMALLOC(-1UL)但这是一个安全的方法吗?
Jim*_*ter 10
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__)
Run Code Online (Sandbox Code Playgroud)
使用您的宏:
#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;
}
Run Code Online (Sandbox Code Playgroud)
警告(应该是一个线索):
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
Run Code Online (Sandbox Code Playgroud)
输出:
p = 0x1, q = 0x1
Run Code Online (Sandbox Code Playgroud)
总之,不,它不是很安全!编写函数可能不太容易出错。
不,它坏了。
似乎假设布尔值或运算符||在被认为是true的情况下返回其参数,而事实并非如此。
C的布尔运算符始终生成1或0为整数,它们不生成任何输入值。
| 归档时间: |
|
| 查看次数: |
5799 次 |
| 最近记录: |