【问题标题】:Function to check for Memory Allocation Errors检查内存分配错误的函数
【发布时间】:2020-05-11 20:28:22
【问题描述】:

我的程序有一堆指针,比如

int* one;
int** two;
int*** three;

我想在对它们使用 realloc 时检查内存分配错误。我知道如果分配失败 realloc 返回NULL 所以我做了以下函数:

void checkMemoryAllocationError(const void *a){
   if (a == NULL){
      fprintf(stderr, "Realloc failed");
      exit(5); //5 is arbitrary
   }
}

我可以通过以下方式调用这个函数吗?

checkMemoryAllocationError(one);
...
checkMemoryAllocationError(two);
...
checkMemoryAllocationError(three);

或者说二和三是指向指针的指针这一事实是否有所不同?我宁愿在我的代码体中重复没有 if 语句,那么这个解决方案是否有效,或者有没有更好的方法来做到这一点,我错过了?

【问题讨论】:

  • 请注意,有许多指向指向指针的指针的实例是程序可以改进的标志。你通常不想成为Three Star Programmer

标签: c realloc


【解决方案1】:

您可以将其包裹在malloc() 周围,而不是调用单独的检查函数:

void *check_malloc(size_t size) {
    void *result = malloc(size);
    if (result == NULL) {
        printf(stderr, "Realloc failed");
        exit(5); //5 is arbitrary
    }
    return result;
}

然后调用check_malloc(),而不是直接调用malloc()

您可以围绕realloc()calloc() 制作类似的包装器。

【讨论】:

    猜你喜欢
    • 2016-07-28
    • 1970-01-01
    • 2016-10-29
    • 1970-01-01
    • 2017-04-07
    • 2010-11-06
    • 2016-09-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多