I’m working on a code I requested from a researching team. I’m trying to understand the code, however, they used malloc in a strange way. here;
in the header file;
#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)
in the cpp file;
double *memRatiosForNNStructs = NULL;
double *listOfRadii = NULL;
nRadii = 1;
FAILIF(NULL == (memRatiosForNNStructs = (double*)MALLOC(nRadii * sizeof(double))));
From my understanding, the MALLOC that they defined means the following;
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
}
Is there something that I’m missing here? Or did they just make a (naive) mistake?
The third code snippet you have is not equivalent. Notice the use of the comma operator:
The comma operator takes two arguments, evaluates and discards the first expression, then evaluates and returns the second expression.
The ternary conditional operator used this way
is equivalent to this
The comma operator used this way
is equivalent to this
So if you have
then that is equivalent to
In the code provided in your original post, the
MALLOCmacro is to be used like this:which is equivalent to this:
Honestly though, this could be achieved as a function in C with no loss of generality:
So I’m not sure what’s the point of even implementing it as a hard-to-read macro.