FMM.MUSTFreeing memory with mismatched functionWhen 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 riskUsing 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 preventionMake sure you use the corresponding allocator and deallocator pairs, as shown in the following table:
Vulnerable code example1 class A { 2 public: 3 void foo(); 4 }; 5 6 void A::foo() 7 { 8 int *ptr; 9 ptr = (int*)malloc(sizeof(int)); 10 delete ptr; 11 } 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 checkersExternal guidanceExtensionThis checker can be extended through the Klocwork knowledge base. See Tuning C/C++ analysis for more information. |