C 用于检查内存分配错误的函数

C 用于检查内存分配错误的函数,c,realloc,C,Realloc,我的程序有很多指针,比如 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

我的程序有很多指针,比如

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语句,那么这个解决方案是否有效,或者是否有一种更好的方法来执行此操作,而我缺少了这种方法?

与其调用单独的检查函数,您可以将其包装在malloc中:

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


您可以围绕realloc和calloc制作类似的包装。

请注意,拥有指向指针的指针的多个实例表明程序可以改进。一般来说,你不想成为一名教师。
void *check_malloc(size_t size) {
    void *result = malloc(size);
    if (result == NULL) {
        printf(stderr, "Realloc failed");
        exit(5); //5 is arbitrary
    }
    return result;
}