CodeQL documentation

Mismatching new/free or malloc/delete

ID: cpp/new-free-mismatch
Kind: problem
Security severity: 7.5
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

  • © GitHub, Inc.
  • Terms
  • Privacy