有什么理由不把 malloc 之后的空检查变成函数吗?

Is there any reason to not turn null check after malloc into a function?

C中,当我们使用malloc系列函数时,我们应该添加一个条件来检查分配是否成功,如果没有,则打印一条消息。

如果我的代码中有很多分配,有什么理由不让这个函数成为一个函数?即:

void nullcheck(void * x){
    if (x == NULL){
        printf("Memory allocation has failed");
        exit(1);
    }
}

并调用函数:

int * a = malloc(sizeof(int));
nullcheck(a);

它使代码更好更短,有什么理由不应该这样做吗?

那(几乎)没问题;只要您每次都以完全相同的方式处理错误。然而;在我看来,一个名为 nullcheck 的函数 returns 什么都没有,并且可能 退出 该程序充其量只是命名不当。

为什么不在一个函数中做所有事情?

void *unrecoverable_malloc(size_t size)
{
    void *x = malloc(size);

    if (x) {
        return x;
    }

    fprintf(stderr, "Memory allocation has failed.\n");
    exit(1);
}

虽然 x = malloc(); if (!x) { /* recover */ } 模式很常见(也是很好的做法),但从 OOM 状态恢复非常困难。它给您一种检查分配失败的温暖和模糊的感觉,但在一个足够复杂的应用程序中,无论您做什么恢复都可能无法正常工作。

is there any reason why it shouldn't be done?

如果您的应用程序能够在分配失败时立即退出,那么请务必将其设为一个函数,甚至将其合并到分配函数中。

如果您正在编写需要比这更好的代码(例如库),则不能这样做,因为通常在释放任何已成功分配的内容后必须返回错误代码。

在后一种情况下,模式如下所示:

p1 = malloc(…);
if (!p1) goto error;
p2 = malloc(…);
if (!p2) goto free1;
p3 = malloc(…);
if (!p3) goto free2;
…
free2:
free(p2);
free1:
free(p1);
error:
return -1;

问:有什么理由不把malloc后的空检查变成函数吗?
A:是:极端情况:分配 0

malloc()calloc() 等返回 NULL 本身并不表示内存不足。

当请求的金额为 0 时,分配函数可能 return NULL。或者,这些函数可以 return 非 NULL 指针。

考虑将 malloc() 和测试放入 1 个函数中。

void *malloc_check(size_t n) {
  void *p = malloc(n);
  if (p == NULL && n > 0) {
    printf("Memory allocation has failed");
    exit(EXIT_FAILURE);
  }
  return p;
}

// or insure `malloc(0)` never occurs.

void *malloc_check(size_t n) {
  if (n == 0) n++;
  void *p = malloc(n);
  if (p == NULL) {
    printf("Memory allocation has failed");
    exit(EXIT_FAILURE);
  }
  return p;
}