FMM.MUST
Freeing memory with mismatched function
When allocated memory is freed or deallocated, it must be done with the corresponding deallocation function. If memory is allocated using one mechanism and released using another-for example, mixing C and C++ memory management functions, or mixing scalar and vector memory management functions-undefined behavior can occur. The FMM.MUST checker flags instances in which mismatched functions have been used to allocate and deallocate memory.
Vulnerability and risk
Using mismatched memory allocation and deallocation functions typically results in unexpected program behavior, and can open the application to denial-of-service (DoS) attacks or memory corruption issues. Particularly in an array of objects, heap memory can be corrupted if the wrong elements of memory are freed. A significant memory leak can occur, which can be exploited as a DoS attack or a program crash.
Mitigation and prevention
Make sure you use the corresponding allocator and deallocator pairs, as shown in the following table:
Allocator | Deallocator |
---|---|
malloc(), calloc(), realloc() | free |
operator new() | operator delete() |
operator new[]() | operator delete[]() |
placement new() | destructor |
Vulnerable code example
class A {
public:
void foo();
};
void A::foo()
{
int *ptr;
ptr = (int*)malloc(sizeof(int));
delete ptr;
}
Klocwork produces a mismatched deallocation report, indicating that the memory pointed by 'ptr' was allocated through the malloc function and released by the delete operator instead of free. A mismatched set of allocator and deallocator like this can result in unpredictable program behavior, and possibly make the application vulnerable to malicious attack.
Related checkers
External guidance
Extension
This checker can be extended through the Klocwork knowledge base. See Tuning C/C++ analysis for more information.