...
The use of type-generic function-like macros is an allowed exception (PRE00-C-EX4) to PRE00-C. Prefer inline or static functions to function-like macros.
Exceptions
MEM02-C-EX1: Do not immediately cast the results of malloc() for code that will be compiled using a C90-conforming compiler because it is possible for the cast to hide a more critical defect (see DCL31-C. Declare identifiers before using them for a code example that uses malloc() without first declaring it).
...
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 | Detectable |
|---|
Repairable | Priority | Level | |
|---|---|---|---|
MEM02-C | Low | Unlikely | Yes |
Yes | P3 | L3 |
Automated Detection
Tool | Version | Checker | Description | ||||||
|---|---|---|---|---|---|---|---|---|---|
| Astrée |
| alloc-without-cast | Partially checked | ||||||
| Axivion Bauhaus Suite |
| CertC-MEM02 | Fully implemented | ||||||
| Compass/ROSE |
Can detect some violations of this recommendation when checking EXP36-C. Do not cast pointers into more strictly aligned pointer types | |||||||||
| ECLAIR |
| CC2.MEM02 | Fully implemented |
5.0
Can detect violations of this rule with CERT C Rule Pack
| Helix QAC |
| C0695 | |||||||
| Parasoft C/C++test |
| CERT_C-MEM02-a | The result of the memory allocation function should be cast immediately | ||||||
| PC-lint Plus |
| 908 | Assistance provided: reports implicit conversions from void* to another type | ||||||
| Polyspace Bug Finder |
| Checks for wrong allocated object size for cast (rule fully covered) | |||||||
| RuleChecker |
| alloc-without-cast | Partially checked |
Related Vulnerabilities
Search for vulnerabilities resulting from the violation of this rule on the CERT website.
Related Guidelines
| SEI CERT C++ Coding Standard | VOID MEM02-CPP. Immediately cast the result of a memory allocation function call into a pointer to the allocated type |
Bibliography
...
...