Windows provides several APIs for allocating memory. While some of these functions have converged over time, it is still important to always properly pair allocations and deallocations. The following table shows the proper pairings.
| Allocator | Deallocator |
|---|---|
malloc() | free() |
realloc() | free() |
LocalAlloc() | LocalFree() |
LocalReAlloc() | LocalFree() |
GlobalAlloc() | GlobalFree() |
GlobalReAlloc() | GlobalFree() |
VirtualAlloc() | VirtualFree() |
VirtualAllocEx() | VirtualFreeEx() |
VirtualAllocExNuma() | VirtualFreeEx() |
AllocateUserPhysicalPages() | FreeUserPhysicalPages() |
AllocateUserPhysicalPagesNuma() | FreeUserPhysicalPages() |
HeapAlloc() | HeapFree() |
HeapReAlloc() | HeapFree() |
Noncompliant Code Example
...
Mixing allocation and deallocation functions can lead to memory corruption issues, or result in accessing out-of-bounds memory.
Rule | Severity | Likelihood |
|---|
Detectable | Repairable | Priority | Level |
|---|---|---|---|
WIN30-C | Low | Probable | No |
No |
P2 |
L3 |
Automated Detection
Tool | Version | Checker | Description | ||||||
|---|---|---|---|---|---|---|---|---|---|
| Astrée |
| Supported: Can be checked with appropriate analysis stubs. | |||||||
| CodeSonar |
| ALLOC.TM | Type mismatch | ||||||
| Coverity |
| ALLOC_FREE_MISMATCH (needs improvement) | Partially implemented; needs improvement | ||||||
| Klocwork |
| FMM.MIGHT FMM.MUST | |||||||
| Parasoft C/C++test |
| CERT_C-WIN30-a | Ensure resources are freed | ||||||
| CERT C: Rule WIN30-C | Checks for mismatched alloc/dealloc functions on Windows (rule fully covered) | |||||||
| PVS-Studio |
| V701 |
Related Vulnerabilities
Search for vulnerabilities resulting from the violation of this rule on the CERT website.
Related Guidelines
...
...