安全malloc/realloc:将调用包装成宏?

Pie*_*rre 5 c malloc macros

我想将我对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)


CB *_*ley 5

使用您的宏:

#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)

总之,不,它不是很安全!编写函数可能不太容易出错。

  • @皮埃尔:不,你*不应该*转换为`char*`;这将隐藏告诉您出现问题的警告! (2认同)

unw*_*ind 5

不,它坏了。

似乎假设布尔值或运算符||在被认为是true的情况下返回其参数,而事实并非如此。

C的布尔运算符始终生成10为整数,它们生成任何输入值。

  • true和false是C99中的宏,您可以选择将其包含在stdbool.h中。C99中`||`的结果仍然是`int`。 (3认同)