With the introduction of pointers to void
in the C Standard, explicitly casting the result of a call to malloc()
is no longer necessary and may even produce unexpected behavior if <stdlib.h>
is accidentally not included.
Non-Compliant Code Example
...
Code Block | ||
---|---|---|
| ||
char *p = (char *)malloc(10);
|
Compliant Solution
By omitting the explicit cast to a pointer, the compiler can determine that an int
is attempting to be assigned to a pointer type and will generate a warning that may easily be corrected.
Code Block | ||
---|---|---|
| ||
#include <stdlib.h>
/* ... */
char *p = (char *)malloc(10);
|
Exceptions
...
Risk Assessment
Explicitly casting the return value of malloc()
may eliminate the warning for the implicit declaration of malloc()
.
Recommendation | Severity | Likelihood | Remediation Cost | Priority | Level |
---|---|---|---|---|---|
MEM02-A | 1 (low) | 1 (unlikely) | 3 (low) | P3 | L3 |
Related Vulnerabilities
Search for vulnerabilities resulting from the violation of this rule on the CERT website.
References
Wiki Markup |
---|
\[[Summit 05|AA. C References#Summit 05]\] [Question 7.7|http://c-faq.com/malloc/cast.html], [Question 7.7b|http://c-faq.com/malloc/mallocnocast.html] |
...