Mismatching new/free or malloc/delete¶
ID: cpp/new-free-mismatchKind: problemSecurity severity: 7.5Severity: warningPrecision: highTags: - reliability - security - external/cwe/cwe-401Query suites: - cpp-code-scanning.qls - cpp-security-extended.qls - cpp-security-and-quality.qls
Click to see the query in the CodeQL repository
This rule findsdelete expressions whose argument is a pointer that points to memory allocated using themalloc function, and calls tofree whose argument is a pointer that points to memory allocated using thenew operator. Behavior in such cases is undefined and should be avoided.
Recommendation¶
Use thedelete operator when freeing memory allocated withnew, and thefree function when freeing memory allocated withmalloc.
Example¶
Record*ptr=newRecord(...);...free(ptr);// BAD: ptr was created using 'new', but is being freed using 'free'
References¶
isocpp.org ‘Standard C++’, “Can I free() pointers allocated with new? Can I delete pointers allocated with malloc()?”
Wikipedia, “Relation to malloc and free” innew and delete (C++).
Common Weakness Enumeration:CWE-401.