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.
Noncompliant Code Example
In this example, the
FormatMessage() function allocates a buffer and stores it in the
buf parameter. From the documentation of
The function allocates a buffer large enough to hold the formatted message, and places a pointer to the allocated buffer at the address specified by lpBuffer. The lpBuffer parameter is a pointer to anL PTSTR; you must cast the pointer to an LPTSTR (for example, (LPTSTR)&lpBuffer). The nSize parameter specifies the minimum number of TCHARs to allocate for an output message buffer. The caller should use the LocalFree function to free the buffer when it is no longer needed.
Instead of freeing the memory using
LocalFree(), this code example uses
The compliant solution uses the proper deallocation function as described by the documentation.
Mixing allocation and deallocation functions can lead to memory corruption issues, or result in accessing out-of-bounds memory.
ALLOC_FREE_MISMATCH (needs improvement)
|Partially implemented; needs improvement|
|Ensure resources are freed|
|CERT C: Rule WIN30-C||Checks for mismatched alloc/dealloc functions on Windows (rule fully covered)|