
...
Calling malloc(s)
allocates memory for an object whose size is s
and returns either a null pointer or a pointer to the allocated memory. A program can implicitly convert the pointer that malloc()
returns into a different pointer type.
...
Noncompliant Code Example
The argument to malloc()
can be any value of (unsigned) type size_t
. If the program uses the allocated storage to represent an object (possibly an array) whose size is greater than the requested size, the behavior is undefined. The implicit pointer conversion lets this slip by without complaint from the compiler.
...
This lets the compiler detect the invalid assignment, because it attempts to convert a gadget *
into a widget *
.
Compliant Solution (hand-coded)
The compliant solution repeats the same type in the sizeof
expression and the pointer cast.
Code Block | ||
---|---|---|
| ||
widget *p; /* ... */ p = (widget *)malloc(sizeof(widget)); |
Compliant Solution (macros)
Repeating the same type in the sizeof
expression and the pointer cast is easy to do, but still invites errors. Packaging the repetition in a macro, such as
...
A small collection of macros can provide secure implementations for common uses for the standard memory allocation functions. The omission of a REALLOC()
macro is intentional (see MEM08-AC. Use realloc() only to resize dynamically allocated arrays).
...
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.
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++.
Recommendation | Severity | Likelihood | Remediation Cost | Priority | Level |
---|---|---|---|---|---|
MEM02-A C | low | unlikely | low | P3 | L3 |
Automated Detection
The LDRA tool suite V 7.6.0 is able to can detect violations of this recommendation.
Fortify SCA Version 5.0 with CERT C Rule Pack can detect violations of this recommendation.
Related Vulnerabilities
Search for vulnerabilities resulting from the violation of this rule on the CERT website.
References
Wiki Markup |
---|
\[[ISO/IEC 9899:1999|AA. C References#ISO/IEC 9899-1999]\] Section 7.20.3, "Memory management functions" \[[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] |
...
08. Memory Management (MEM) MEM03-AC. Clear sensitive information stored in reusable resources returned for reuse