Semmle 1.20
Skip to end of metadata
Go to start of metadata

Name: Mismatching new/free or malloc/delete

Description: An object that was allocated with 'malloc' or 'new' is being freed using a mismatching 'free' or 'delete'.

ID: cpp/new-free-mismatch

Kind: problem

Severity: warning

Precision: high

Query: NewFreeMismatch.ql
/**
 * @name Mismatching new/free or malloc/delete
 * @description An object that was allocated with 'malloc' or 'new' is being freed using a mismatching 'free' or 'delete'.
 * @kind problem
 * @problem.severity warning
 * @precision high
 * @id cpp/new-free-mismatch
 * @tags reliability
 *       security
 *       external/cwe/cwe-401
 */
import NewDelete

/**
 * Holds if `allocKind` and `freeKind` indicate corresponding
 * types of allocation and free.
 */
predicate correspondingKinds(string allocKind, string freeKind) {
  (
    allocKind = "malloc" and
    freeKind = "free"
  ) or (
    allocKind = "new" and
    freeKind = "delete"
  )
}

from
  Expr alloc, string allocKind, string allocKindSimple,
  Expr free, Expr freed, string freeKind, string freeKindSimple
where
  allocReaches(freed, alloc, allocKind) and
  freeExprOrIndirect(free, freed, freeKind) and
  allocKindSimple = allocKind.replaceAll("[]", "") and
  freeKindSimple = freeKind.replaceAll("[]", "") and
  not correspondingKinds(allocKindSimple, freeKindSimple)
select free, "There is a " + allocKindSimple + "/" + freeKindSimple + " mismatch between this " + freeKind + " and the corresponding $@.", alloc, allocKind

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