c++ - 为什么要这样使用 malloc?

标签 c++ memory malloc

我正在研究我向研究团队请求的代码。我试图理解代码,但是,他们以一种奇怪的方式使用了 malloc。在这里;

在头文件中;

 #define ERROR_OUTPUT stderr
 #define FAILIF(b) {   \
   if (b) {  \
       fprintf(ERROR_OUTPUT, "FAILIF triggered on line %d, file %s. Memory allocated: %lld\n",  \
       __LINE__, __FILE__, totalAllocatedMemory); exit(1); \
   } \
  }
 #define MALLOC(amount) \ 
   ( (amount > 0) ? totalAllocatedMemory += amount, malloc(amount) : NULL)

在cpp文件中;

 double *memRatiosForNNStructs = NULL;
 double *listOfRadii = NULL;
 nRadii = 1;
 FAILIF(NULL == (memRatiosForNNStructs = (double*)MALLOC(nRadii * sizeof(double))));

根据我的理解,他们定义的MALLOC意思如下;

if(amount>0) // which is true; at least in this case
{
   totalAllocatedMemory = totalAllocatedMemory + amount; // sounds reasonable
   malloc(amount)  // What?? This will leak memory...
}
else
{
   NULL; // Do nothing? I guess that's fine
}

我在这里遗漏了什么吗?或者他们只是犯了一个(天真的)错误?

最佳答案

您拥有的第三个代码片段不等效。注意使用 the comma operator :

#define MALLOC(amount) \
    ( (amount > 0) ? totalAllocatedMemory += amount, malloc(amount) : NULL)  
                                                   ^
                                                  N.B.!

逗号运算符接受两个参数,计算并丢弃第一个表达式,然后计算并返回第二个表达式。

ternary conditional operator以这种方式使用

a = ((b)?(c:d))

相当于这个

if(b) {
    a = c;
}
else {
    a = d;
}

逗号操作符是这样用的

e = f, g;

相当于这个

f;
e = g;

如果你有

a = ((b)?(f,g:d))

那么相当于

if(b) {
    f;
    a = g;
}
else {
    a = d;
}

在您的原始帖子中提供的代码中,MALLOC 宏将像这样使用:

memRatiosForNNStructs = (double*)MALLOC(nRadii * sizeof(double));

相当于:

   // First operand of ternary conditional
if(nRadii * sizeof(double) > 0)
{
    // Second  operand of ternary conditional

    // First expression of the comma operator
    totalAllocatedMemory += nRadii * sizeof(double));
    // Second expression of the comma operator
    memRatiosForNNStructs = (double*)malloc(nRadii * sizeof(double));
}
else
{
    // Third operand of ternary conditional
    memRatiosForNNStructs = (double*)NULL;
}

老实说,这可以作为 C 中的一个函数来实现而不失一般性:

void* my_malloc(unsigned int amount)
{
    if(amount > 0) {
        // I assume this is a global variable
        totalAllocatedMemory = totalAllocatedMemory + amount;
        return  malloc(amount);
    }
    else {
        return NULL;
    } 
}

memRatiosForNNStructs = (double*)my_malloc(nRadii * sizeof(double));

所以我不确定将其实现为难以阅读的宏有什么意义。

关于c++ - 为什么要这样使用 malloc?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9154412/

相关文章:

c++ - 如何隐藏菜单? lpsz菜单名

c - 如何管理硬件缓存使用

memory - 内存地址是什么意思?

c - 将 csv 文件读入结构数组

c++ - 没有源代码的gdb中的方法定义

c++ - 调用x64汇编函数后C++变量重置为0

c++ - 我不能直接在 C++ 中返回列表初始化吗?

c - 请解释这个对齐错误

c - Valgrind 1017 calloc/memcopy of struct dirent OK,第 1018 次 -- 无效读取

c - 为什么 realloc 不缩小数组?