...
The use of type-generic function-like macros is an allowed exception (PRE00-EX4) to PRE00-C. Prefer inline or static functions to function-like macros.
Exception
When compiling a 64-bit application on an LP64 or LLP64 platform, this recommendation should not be used because it is possible for the cast to hide a bug. If stdlib.h
is not properly included, the compiler will assume the declaration of malloc
() to be int malloc()
. When sizeof(int)
on the platform is 4, the resulting pointer could be truncated due to the compiler assuming malloc()
returns a 32-bit integer. Additionally, casting the results of malloc()
to a pointer on these platforms can also sign extend a negative 32-bit integer to an invalid pointer.
Code Block | ||||
---|---|---|---|---|
| ||||
/* #include <stdlib.h> is missing */
int main() {
int i;
for (i = 0; i < 100; ++i) {
char *ptr = (char*)malloc(0x10000000); /* int malloc() assumed */
*ptr = 'a';
}
return 0;
}
|
On an LLP64/LP64 platform, such as Microsoft Windows, the above code will eventually cause an access violation when dereferencing ptr in the loop.
Risk Assessment
Failing to cast the result of a memory allocation function call into a pointer to the allocated type can result in inadvertent pointer conversions. Code that follows this recommendation will compile and execute equally well in C++.
...