我正在研究我要求研究团队提供的代码.我试图理解代码,然而,他们以一种奇怪的方式使用了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)
Run Code Online (Sandbox Code Playgroud)
在cpp文件中;
double *memRatiosForNNStructs = NULL;
double *listOfRadii = NULL;
nRadii = 1;
FAILIF(NULL == (memRatiosForNNStructs = (double*)MALLOC(nRadii * sizeof(double))));
Run Code Online (Sandbox Code Playgroud)
根据我的理解,他们定义的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
}
Run Code Online (Sandbox Code Playgroud)
这里有什么我想念的吗?或者他们只是犯了一个(天真的)错误?
你拥有的第三个代码片段并不等同.注意使用逗号运算符:
#define MALLOC(amount) \
( (amount > 0) ? totalAllocatedMemory += amount, malloc(amount) : NULL)
^
N.B.!
Run Code Online (Sandbox Code Playgroud)
逗号运算符接受两个参数,计算并丢弃第一个表达式,然后计算并返回第二个表达式.
在三元条件操作中使用这种方式
a = ((b)?(c:d))
Run Code Online (Sandbox Code Playgroud)
相当于此
if(b) {
a = c;
}
else {
a = d;
}
Run Code Online (Sandbox Code Playgroud)
逗号运算符使用这种方式
e = f, g;
Run Code Online (Sandbox Code Playgroud)
相当于此
f;
e = g;
Run Code Online (Sandbox Code Playgroud)
所以,如果你有
a = ((b)?(f,g:d))
Run Code Online (Sandbox Code Playgroud)
那相当于
if(b) {
f;
a = g;
}
else {
a = d;
}
Run Code Online (Sandbox Code Playgroud)
在原始帖子中提供的代码中,MALLOC
宏的使用方式如下:
memRatiosForNNStructs = (double*)MALLOC(nRadii * sizeof(double));
Run Code Online (Sandbox Code Playgroud)
这相当于:
// 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;
}
Run Code Online (Sandbox Code Playgroud)
老实说,这可以作为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));
Run Code Online (Sandbox Code Playgroud)
所以我不确定将它作为一个难以阅读的宏实现的重点是什么.
归档时间: |
|
查看次数: |
249 次 |
最近记录: |