我正在研究我向研究团队请求的代码。我试图理解代码,但是,他们以一种奇怪的方式使用了 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/