Mismatching new/free or malloc/deleteΒΆ
ID: cpp/new-free-mismatch
Kind: problem
Severity: warning
Precision: high
Tags:
- reliability
- security
- external/cwe/cwe-401
Query 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 finds delete expressions whose argument is a pointer that points to memory allocated using the malloc function, and calls to free whose argument is a pointer that points to memory allocated using the new operator. Behavior in such cases is undefined and should be avoided.
RecommendationΒΆ
Use the delete operator when freeing memory allocated with new, and the free function when freeing memory allocated with malloc.
ExampleΒΆ
Record *ptr = new Record(...);
...
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β in new and delete (C++).
- Common Weakness Enumeration: CWE-401.