With the introduction of void *
pointers in the ANSI/ISO 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 not included.
If stdlib.h
is not included, the compiler makes the assumption that malloc()
has a return type of int
. When the result of a call to malloc()
is explicitly cast to a pointer type, the compiler assumes that the cast from int
to a pointer type is done with full knowledge of the possible outcomes. This may lead to behavior that is unexpected by the programmer.
char *p = (char *)malloc(10); |
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.
#include <stdlib.h> /* ... */ char *p = malloc(10); |
The return value from malloc()
may be cast in C code that needs to be compatible with C++, where explicit casts from void *
are required.
Explicitly casting the return value of malloc()
eliminates 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 |
Search for vulnerabilities resulting from the violation of this rule on the CERT website.
\[[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] |
MEM01-A. Eliminate dangling pointers 08. Memory Management (MEM) MEM03-A. Clear sensitive information stored in dynamic memory prior to deallocation